File handling is the method of storing the data generated by a program in a file or taking the data of a file as input to the program. It is an integral part of most programming languages. Python provides built-in functions to perform file operations.
Today in this article I will discuss different file operations in Python for example opening or creating a file, reading from it, writing to it, appending data to an existing file, and finally closing an opened file.
Opening and closing a file in Python
Before you perform any operation like reading, writing, or appending to a file first you need to open it. In Python, the open() function is used for opening a file its basic syntax is given below.
f= open('filename', 'mode')
filename – Name of the file that you are going to open to perform an operation
mode – It specifies the operations that we are going to perform on a file it could be read, write, append, etc.
In Python following file modes are supported –
r– Open an existing file for the read operation, and returns an error if the file is not found (this is the default mode)
w– Open a file for the write operation if the file is not found it will create a new one. It will override the data of the existing file.
a– Open a file in append mode, in this mode you can add data to an existing file. The data already present will not be overridden.
t– Open a file in text mode (This is the default mode)
b– Open a file in binary mode. Use this mode for non-textual files like images.
+– Open a file for updating (reading and writing)
After performing the operations on opened file you can close it by using –
It is recommended to use the opening and closing file statement in a try…finally block to make sure the file is closed properly even when there is an exception is raised.
try: f = open("filename", "mode") # perform file operations here finally: f.close()
Another way to open a file is by using the
with keyword –
with open("filename", "mode") as f: # here perform the file operations
When a file is opened in the given way you don’t need to call the close() method explicitly instead it is handled automatically so it is considered the best method for opening a file.
Performing file operations
You can perform various file operations such as reading, writing, appending, etc in Python. Some examples are given below.
Writing to a file
To write some data into a file you need to open the file in ‘w’ or ‘a’ mode. Writing to a file in Python is done through the write() method.
# First open the file in write mode f = open('sample.txt','w') # start writing with write() method f.write("Hi\n") f.write("This is sample text file\n") f.write("created in Python\n") # Finally close the file f.close()
The implementation of the above code using the with keyword is given below.
with open("sample.txt", 'w') as f: f.write("Hi\n") f.write("This is sample text file\n") f.write("created in Python\n")
When you execute this code a file with the name sample.txt will be created and given three lines will be written to it. If this file already exists then the content of that file will be overridden.
Reading a file
There are various methods of reading a file in Python. First, use the read() method to read the content of a file. Also, you need to open the file in ‘r’ mode.
with open("sample.txt",'r') as f: print(f.read(), end='')
When you execute the above code it will print the whole content of a file.
To read the first n number of characters of a file use read(n) method for example –
with open("sample.txt",'r') as f: print(f.read(7), end='')
This will read the first 7 characters including white spaces of the file sample.txt. You can see the output of the above code in the below image.
To read a file line by line, use the readline() method.
with open("sample.txt", 'r') as f: # Given statement will print the first line print(f.readline()) # This will print the second line print(f.readline())
The above code will print the first two lines of the file sample.txt, as you can see the output in the given image.
Using the readlines() method will print all the content of a file in the form of a list where elements of the list will be lines of the file.
with open("sample.txt", 'r') as f: print(f.readlines())
When you will execute this code you will see an output something like the given in the image below.
All the reading methods discussed here will return the EOF character when reached at the end of the file.
Appending to a file
When we want to add some information to an existing file we will open the file in ‘a’ i.e. append mode, It will place the pointer at the end of the file. If the file doesn’t exist then it will create a new one.
with open("sample.txt", 'a') as f: f.write("This line is added to sample.txt file\n")
Once the above code is executed the given text will be added to the end of the file sample.txt. Using the given code you can view the content of the file.
with open("sample.txt", 'r') as f: print(f.read())
This will display the given output.
For more information, you can view Python’s official documentation.
So here you have learned how to perform different operations on a file in Python. Now if you have a query or feedback then write us in the comments below.