DEV Community

Cover image for basics of file handling in python
Jordan Kalebu
Jordan Kalebu

Posted on • Updated on

basics of file handling in python

The original article can be found at kalebujordan.dev
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 which contains quotes as shown below;

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.
Enter fullscreen mode Exit fullscreen mode
  • 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.
Enter fullscreen mode Exit fullscreen mode

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

Diving into the basics

  • 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)

You should use this mode when you're opening a file with the intention to read its content only since once you open a file in reading mode, it restricts you from making any changes to it.

To open a file in reading mode you just specify the path to the file plus the reading mode which r just as shown below;

file = open('quotes.txt', 'r')

data = file.read()

print(data)
Enter fullscreen mode Exit fullscreen mode

When you run the above code it will print the same result as the one we have seen above.

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

>>> 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'
Enter fullscreen mode Exit fullscreen mode

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.
***********************************
Enter fullscreen mode Exit fullscreen mode

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 the 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.
Enter fullscreen mode Exit fullscreen mode
  • 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 inaccessible to other programs.

Therefore to prevent that you’re advised to open a file using a 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.
Enter fullscreen mode Exit fullscreen mode

Working with writing mode

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

We normally use mode when a 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 a few numbers into:

  • Example of Usage :
>>> with open('numbers.txt', 'w') as file:
...     for number in range(10):
...             file.write(str(number))
... 
Enter fullscreen mode Exit fullscreen mode

If you open your number.txt you find 0123456789 is written to it.

Working with appending mode

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

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

  • Example of Usage
>>> with open('quotes.txt', 'a') as file:
...     new_quote = '\nThe world is tragedy to tho who feel'
...     file.write(new_quote)
... 
36
----------reading the file again---------------------
>>> lastline = open('quotes.txt').readlines()[-1]
>>> print(lastline)
The world is a tragedy to tho who feel
Enter fullscreen mode Exit fullscreen mode

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

*Follow me on Twitter

I recommend also reading this;

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

Top comments (0)