DEV Community

Bamimore-Tomi
Bamimore-Tomi

Posted on

File Handling With Python

At some point in programming, you will have to work with files. You will come across things like File IO, File Buffer, and other jargon. In this post, we will explore file handling in Python: methods, procedures, and rules.

Please note that to understand this article, you need to have a basic understanding of Python’s syntax.

With or …

Python provides an inbuilt function to open files. You probably know that already. There are two ways to implement the function.
image
The inbuilt function open returns a stream. In this case, the stream allows you to continuously read or write to the file you opened. The open function takes a couple of arguments which we will explore.
image

The file argument is the name of the file you want to open in Python. It is usually a string containing the name and extension e.g. my_file.txt.
The mode is an optional argument that usually defaults to ‘r’. There are other options for the mode argument. You should specify the mode argument if you want to perform any operation apart from reading from a file. Here is a list of other options.
image
Next up is the buffering argument. Buffering is an integer used to set the buffering policy. This may sound a little strange. You can read this page to understand the concept of buffering as it relates to file handling in python.

Another optional argument is encoding. The default encoding is platform-dependent. This is only applicable in text mode, you can check the list of encodings available in python here.

You can read about the other arguments here.

One important thing to note when dealing with files is the with statement. The with statement ensures the acquisition and release of resources. If you use the with statement to access a file, it is certain that the file will always be closed. To use the with statement to manage your objects, check out this example.
image

Reading, Writing and Appending Operation

In this section, we will be helping a teacher sort and compute the average of students' grades into a file.
image
A few moments later …
image
See the result of this set of operations on the input file below
image
We forgot to add the teacher’s signature to the output file. To solve the problem, we open the file in append mode to avoid overwriting previously written data.
image
The new output file looks like this.
image

File handling is not only limited to .txt files. You may have to work with files in other formats and the same rules apply. Thanks for reading.

Top comments (0)