In real world applications, we often need to read data from files and write data into files. In this article, we will study file handling in python and will implement different operations like python read file, write to file and append to file using different functions in python.
Open a file in Python
To open a file in python, we can use the open() function. Generally two input arguments are passed to the open() function. The first argument is the filename which needs to be opened and the second argument is the mode in which the file has to be opened. The most common mode parameters are defined as follows.
- “r” mode is used for opening a file in read only mode.
- “w” mode is used for opening a file in write mode. It also overwrites the existing file with the same name or creates a new file if it doesn’t exist.
- “a” mode is used for opening a file in append mode. It creates a new file if the file doesn’t exist but it doesn’t overwrite the file if it already exists.
- “b” mode is used to open a file in binary mode.
The open() function returns a file object on successfully opening the file. A file can be opened using specifying the filename and mode as follows.
myFile=open("filename.txt",mode="r")
We can also specify the encoding for the file as the third input argument. By default the encoding is dependent on the operating system. We can explicitly specify the encoding as follows.
myFile=open("filename.txt",mode="r",encoding="UTF-8")
Close a file
In python, we must close all the opened files before termination of the program using the close() method. The close() method when invoked on a file object closes the file. While doing file operations, we must use exception handling using python try except and invoke the close() method in finally block so that file gets closed even if any error occurs during execution of the program. An opened file can be closed using close() method as follows.
myFile.close()
Read from the file
After opening the file, we can read the data from the file using read() method. The read() method takes an optional argument as input to specify the number of characters to be read from the file. If the read() method is invoked on the file object without any argument, it reads the whole file and returns it as a text string. This can be seen in the following example.
try:
myFile=open("/home/aditya1117/filename.txt",mode="r")
print(myFile.read())
except Exception as e:
print(str(e))
finally:
myFile.close()
Output:
This is a sample text file.
This file is for PythonForBeginners.com.
This file has been written by Aditya Raj for demonstration.
We can read a certain number of characters from the file as follows.
try:
myFile=open("/home/aditya1117/filename.txt",mode="r")
print(myFile.read(21))
except Exception as e:
print(str(e))
finally:
myFile.close()
Output:
This is a sample text
We can also read a file line by line using the readline() method as follows.
try:
myFile=open("/home/aditya1117/filename.txt",mode="r")
print(myFile.readline())
except Exception as e:
print(str(e))
finally:
myFile.close()
Output:
This is a sample text file.
We can also iterate over a file using a for loop. In this way the iterator iterates the file object line by line. This can be seen as follows.
try:
myFile=open("/home/aditya1117/filename.txt",mode="r")
for line in myFile:
print(line)
except Exception as e:
print(str(e))
finally:
myFile.close()
Output:
This is a sample text file.
This file is for PythonForBeginners.com.
This file has been written by Aditya Raj for demonstration.
Write to file in Python
We can write any string to the opened file using the write() method as follows.
try:
myFile=open("/home/aditya1117/filename1.txt",mode="w")
myFile.write("This string is being added to the file.")
except Exception as e:
print(str(e))
finally:
myFile.close()
When a file is opened in “w” mode, it overwrites the existing file. If we want to keep the previous data as it was and add new data to it, we can open the file using append mode denoted by “a” as follows.
try:
myFile=open("/home/aditya1117/filename1.txt",mode="a")
myFile.write("This string is being appended to the file.")
except Exception as e:
print(str(e))
finally:
myFile.close()
Conclusion
In this article, we have understood the concept of file handling in python. We have seen how to open a file, read data from it, write data into the file and then close the file. Stay tuned for more informative articles.
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.