File handing in Python

I recently started reading the pym book suggested by folks at #dgplug. Since I have been programming in Python since an year and a half, I could go through the basics fairly quick. Here are the topics I covered:

However, file handling is something I have rarely used till now. This blog talks about the it and some of the great takeaways.

Opening a file

A file can be opened in three modes: ### Read: Opens the file in read-only mode. The file cannot be edited or added content to. The syntax for the same is :

>>> f = open('requirements.txt' , 'r')

### Write: Opens the file in write, you can make desired changes to the file. The syntax for the same is:

>>> f = open('requirements.txt' , 'r')

### Append: Opens file in append mode. You can append further content, but cannot change or modify past content. The syntax for the same is:

>>> f = open('requirements.txt' , 'a')

Reading a file

When a file is openened in read mode, the file pointer is at the beginning of the file. There are different functions for reading the file:

read()

It reads the entire file at once. The file pointer traverses the entire file on calling this function. Therefore, calling this function again will have no effect, since the file pointer is already at EOF. Syntax for the same is:

>>> f.read()
'selenium >= 3.141.0\npython-telegram-bot >= 11.1.0\ndatetime >= 4.3\nargparse >= 1.4.0\nwebdriver-manager >= 1.7\nplaysound >= 1.2.2'

readline()

This function moves the file pointer to the beginning of the next line hence outputting one line at a time. Syntax for readline() function is :

>>> f.readline()
'selenium >= 3.141.0\n'
>>> f.readline()
'python-telegram-bot >= 11.1.0\n'

readlines()

Reads all the lines in a file and returens a list.

>>> f.readlines()
['selenium >= 3.141.0\n', 'python-telegram-bot >= 11.1.0\n', 'datetime >= 4.3\n', 'argparse >= 1.4.0\n', 'webdriver-manager >= 1.7\n', 'playsound >= 1.2.2']

Now, we should always close a file we opened when not in use. Not closing it increases memory usage and degrades the quality of code. Python offers nice functionality to take care of file closing by itself:

with keyword

`with keyword can be used as follows:

>>> with open('requirements.txt' , 'r') as f:
...     f.read()
... 
'selenium >= 3.141.0\npython-telegram-bot >= 11.1.0\ndatetime >= 4.3\nargparse >= 1.4.0\nwebdriver-manager >= 1.7\nplaysound >= 1.2.2'

Writing into a file

The .write() function can be easily used to write into a file. This will place the file pointer to the beginning and over-write the file completely. Here's how that works:

>>> f = open('requirements.txt' , 'w')
>>> f.write('tgbot\n')
6

The return value '6' denotes the number of characters written into the file

Hope you enjoyed reading the blog, :)