Kalebu Jordan

Become a Pro Python Developer

File handling in Python

Hi guys

In this article you’re going to learn how to work with files in python, you gonna learn various techniques on how open, read, manipulate, and save files in python.

Once you finish this article you will be in a good position of handling files in python so I suggest you read this to the end.

Getting started

Working with files in python is straightforward, you can open files and read it in just one line of code.

For instance, let’s try reading quotes.txt from a file

True humility is not thinking less of yourself; it is thinking of yourself less.
I believe in Christianity as I believe that the sun has risen: not only because I see it, but because by it I see everything else.
You are never too old to set another goal or to dream a new dream.

Reading from file

>>> data = open('quotes.txt').read()
>>> print(data)
True humility is not thinking less of yourself; it is thinking of yourself less.
I believe in Christianity as I believe that the sun has risen: not only because I see it, but because by it I see everything else.
You are never too old to set another goal or to dream a new dream.

We used the open ( ) function to read a file in python in just one line of code.

Modes of opening files in Python

You can open a file in python in different modes such as reading mode, writing mode, appending mode, binary mode and etc.

By default, python opens the files in reading mode thus why in the example above we didn’t specify the mode but it doesn’t throw any error.

We use the following abbreviation to specify the mode;

  • r -> for opening file in reading mode
  • w ->for opening file in writing mode
  • a -> for opening file in appending mode
  • r+ ->for opening file in reading and writing mode
  • w+ ->for opening file in writing and reading mode
  • rb -> for reading in binary mode
  • wb -> for writing in binary mode

Reading files in python (reading mode)

The syntax for opening files in python in a reading mode is ;

>>> file = open(filename , mode)
Reading mode
>>>file = open('quotes.txt', 'r')

Once you open a file using the open ( ) function it creates a file object with different methods that you can use to manipulate the file which can be viewed by the dir ( ) method.

>>> dir(file)
.................
'buffer', 'close', 'closed', 'detach', 'encoding', 'errors',
'fileno', 'flush', 'isatty', 'line_buffering', 'mode', 'name',
'newlines', 'read', 'readable', 'readline', 'readlines', 'seek',
'seekable', 'tell', 'truncate', 'writable', 'write', 'writelines'

There is a way to read the entire file and also line by line, for instance, let’s try reading line by line and after each line, we print a line of stars.

Reading by line by line
>>> file = open('quotes.txt', 'r')
>>> for line in file:
...     print(line)
...     print('***********************************')
... 
True humility is not thinking less of yourself; it is thinking of yourself less.

***********************************
I believe in Christianity as I believe that the sun has risen: not only because I see it, but because by it I see everything else.

***********************************
You are never too old to set another goal or to dream a new dream.
***********************************
Reading a specific line

you can also a specific line you need , for instance Let’s try reading the only seconds from our quotes.txt

Note :
Index starts with 0 , from bottom of the file to the top of the file

>>> file = open('quotes.txt', 'r')
>>> second_line = file.readlines(1)[0]
>>> print(second_line)
I believe in Christianity as I believe that the sun has risen:
not only because I see it, but because by it I see everything else.
Reading the entire file at once
>>> file = open('quotes.txt', 'r')
>>> document = file.read()
>>> print(document)
True humility is not thinking less of yourself; it is thinking of yourself less.
.........

Note :
When you open a file in Python you need to close it once you finish manipulating with it because not closing it may make it in accessible to other program.

Therefore to prevent that you’re advised to open a file using with statement, which will automatically close the file when the block code finished running .

Example of Usage

>>> with open('quotes.txt', 'r') as file:
...     line = file.readline()
...     print(line)
... 
True humility is not thinking less of yourself; it is thinking of yourself less.

Working with writing mode

To open a file in writing mode you need to use abbreviation of w on reading mode.

We normally use mode when new file to write information into because if you use this mode to open an existing file , it will replace the existing file content with the one you just wrote

For instance Let’s open a new file called numbers and then write few numbers into:

Example of Usage :

>>> with open('numbers.txt', 'w') as file:
...     for number in range(10):
...             file.write(str(number))
... 

If you open your number.txt it will look as shown below

0123456789

Working with appending mode

Appending mode is used when we want to append new information to existing file, to open file in appending mode use a on file mode .

For instance Let’s add new quote to our quotes.txt

Example of Usage :

>>> with open('quotes.txt', 'a') as file:
...     new_quote = 'The world is tragedy to tho who feel'
...     file.write(new_quote)
... 
36
----------reading the file again---------------------
>>> lastline = open('quotes.txt').readlines()[-1]
>>> print(lastline)
You are never too old tohe  set another goal or to dream a new dream.
The world is tragedy to tho who feel

As you can in appending mode the quote we just added just saved to our file revealed when when we try open it again.

Hope you find this post interesting, don’t forget to subscribe to get more tutorials like this.

I recommend also checking this;

In case of any suggestion or comment, drop it in the comment box and I will get back to you ASAP.

One thought on “Learn how to working with files in python

Leave a Reply

error

Enjoy this blog? Please spread the word :)