File handling in Python
File handling in Python
Files are named locations which store information. We can permanently store data using files in a non-volatile memory like a hard disk. As RAM(Random Access Memory) is volatile and will store the information temporarily , we use files for storing them permanently.
Python supports file handling i.e., opening a file, reading from it, writing into it, closing it, and various file methods which are used to operate on files. Various other languages support file handling, but its implementation is either too complicated or long. But Python on the other hand, just like its other concepts which are easy and short, file handling is also much simpler. Let’s begin by learning how to read and write files. In order to read from or write to a file, we need to open it , and then once the task is done, we have to close it.
Python has a built-in open() function to open a file. This function returns a file object, also called a handle. To return this file object we use the open() function along with two arguments file name and mode.
Syntax: open(filename, mode).
We can also specify the entire path of the path in the place of the file name.
The below mentioned are different modes in which we can open a file
r: opens a file for reading.
w: opens a file for writing.
x: creates a file and opens it. The operation will be failed If the file already exists.
a: opens a file and appends the file at the end without replacing or deleting the existing content.
t: opens file in text mode.
b: opens file in binary mode.
+: opens a file in both reading and writing modes.
Note: If the mode is not specified a file opens in text and reading mode. While we are using this mode, we get strings when reading from the file. On the other hand, binary mode returns bytes and this is the mode to be used when dealing with non-text files like images or executable files. Also, in the w and a modes a new file is created if it doesn’t exist.
We need to properly close the file once we are done with doing operations on the file. Closing a file will free up the resources that were tied with the file. We can achieve this by using the built-in close() function. Python already clears up all the unreferenced objects using the Garbage Collector but we must close the file and not rely on it.
This method is not that safe to use. When we are performing some operations on the file, and an exception gets raised, the code exits without closing the file.
Using a try…finally block is a much safer option.
Even if an exception is raised it doesn’t pause or stop the program’s flow and it ensures that the file is properly closed. One of the other best ways to close a file is using the with statement. Here, we need not explicitly call the close() method, it is done internally.
Writing to Files:
We’ll have to open it in either w or a or x mode.
While using the file in w mode we need to be careful, because if the file already exists it will be overwritten into the file and clears out all the previous data. Using the write() function we can write a string or sequence of bytes (for binary files). It will return the number of characters written to the file.
The above-mentioned example code creates a new file named i2tutorilas.txt in the current directory if it doesn’t exist. In case if it does exist, it gets overwritten. To separate different lines we must include the newline characters.
The in-built read(size) method is used to read the size number of data. It reads and returns till the end of the file if the size parameter is not specified.
We can see that the read() method returns a newline as ‘\n’. Once the end of the file is reached, we get an empty string on further reading.
Note: Using the seek() method, we can change our current file cursor position and using the tell() method, we can know the current position in the form of number of bytes.
Refer this article to know how to read line by line from a file into a list (Please add back link here)(https://www.i2tutorials.com/how-to-read-a-file-line-by-line-into-a-list/)
We also have the readline() method which reads individual lines of a file till the newline, including the newline character.
And finally, the readlines() method returns a list of remaining lines of the entire file.
When the end of the file is reached, the read(size), the readline() and the readlines() methods return empty string(values).
Python File Methods:
These are some of the file methods available in Python in text mode: