File I/O in python. This is the most commonly used and one of the most important topics in Python.
Why do we use files?
In python, we can provide inputs to our program through input() and provide output of the program using print() but will that last for long time? Answer is no, as the data is stored in temporary memory location and will be vanished once the program is closed. So what to do when you want to store the output of the program somewhere so that we can refer it afterwords, at that time 'files' come into picture. We can supply files as input to the python program or also can store the output of program in files.
File operations:
Following are the important operations while working with files:
Open the file
Read/write/append the content in the file
Close the file : It is important to free up the resources after completing the script.
How to open the file?
One way to open the file is using open():
f = open("test1.txt",'r')
Another way is:
with open('test1.txt', 'r') as reader:
# Do the further operations
The important difference in above two ways is that, by using first way we have to explicitly close the file but in case of using with statement the closure of file is automatically done as internal activity. So it is always better to prefer second way while working with files.
File can be opened in following modes:
After opening the file we will need to read it.
How to read the file?
Following are the methods to read the file.
Suppose our text file has following content:
Hello, I love Avatar: The Last Airbender Series.
My favourite character is Toph.
So how above content from file test.txt is read in three reading methods is as shown below:
.read()
with open('test1.txt', 'r') as file_obj:
# Read & print the entire file
print(file_obj.read())
Output:
Hello, I love Avatar: The Last Airbender Series.
My favourite character is Toph.
.readline()
with open('test1.txt', 'r') as file_obj:
# Read & print the first 5 characters of the line 4 times,
# and once end of line is reached it starts printing second line
# for specified characters
print(file_obj.readline(5))
print(file_obj.readline(5))
print(file_obj.readline(5))
print(file_obj.readline(5))
Output:
Hello
, I l
ove A
vatar
.readlines()
with open('test1.txt', 'r') as file_obj:
# will print the lines as list
print(file_obj.readlines())
Output:
['Hello, I love Avatar: The Last Airbender Series.\n', 'My favourite character is Toph.']
You can use for loop to print the output line by line, my intention was to show you difference between working of different methods.
Now let's see how to write to the file:
Suppose we want to write only second line to tophfan.txt from test1.txt by using .write(string)
with open('test1.txt', 'r') as file_obj:
reader = file_obj.readlines()
with open('tophfan.txt','w') as f:
f.write(reader[1])
Output:
#tophfan.txt
My favourite character is Toph.
Usage of .writelines(iterable): : Here I want to print whole data in tophfan.txt
with open('test1.txt', 'r') as file_obj:
reader = file_obj.readlines()
with open('tophfan.txt', 'w') as f:
f.writelines(reader)
Output:
#tophfan.txt
Hello, I love Avatar: The Last Airbender Series.
My favourite character is Toph.
Closing the file
As earlier mentioned, it is important to free up the resources after completing the script. So how to close the file?
There are two ways to achieve closure of file:
One by using try...finally block:
try:
f = open("test.txt")
# perform file operations
finally:
f.close()
Other by using 'with' statement as stated above, here closure of file is taken care automatically:
with open('test1.txt', 'r') as reader:
# Do the further operations
That's all for today's article. Till then keep coding, keep learning!