Python File operations : Open, Close, Read , Write and Append to a file in Python :
Python has functions and methods to manipulate files . No external library is required for doing file operations in python. In this tutorial, we will learn different python file operations like reading the content of a file, writing to a file etc.
Why file operations are important ? If you want to store something that can be accessible even after system is restarted , then store it in a file. Files are stored in non volatile memory of a system, so they are available even after the program is terminated.
Create a file in python :
Lets try to create one “.txt” file first . Before doing any operation on a file, first we must open it using built-in open() function. Create one file “file_operation.py” and enter the following :
f = open(“myfile.txt","w”)
Now run this file and check the folder : a new file “myfile.txt” should be present there.
We are using open() function to open a file “myfile.txt” in the folder. It takes two argument : first one is the file name we want to open and second one is the mode of operation for that file. This function returns a file object which can be used to modify and read the file .
Mode of operation can be different . Here we are using “w” , that means it will open a file for reading and writing . If the file is not available, it will create a new file.
Following are the different modes and description :
1. Does not create a new file if file is not present :
r : open a file for reading .
rb : open a file for reading in binary format.
2. Create a new file if the file is not present :
w : Open a file for writing . wb : Open a file for writing in binary format.
a : Open a file for appending.
ab : Open a file for appending in binary format.
We can also use** a +** sign with all of these operations. For** “r”** and “rb” , it will be open for both read and write. For** “w”** and “wb”, it will be same : open for both read and write. Similarly, for** “a”** and “ab”, it will be for both appending and reading.
For binary data files like image ,songs etc. , if you are trying to do read and write ,always make sure to use binary mode ‘b’, otherwise it might corrupt the file.
Closing a file :
After we done editing the file, we should always close it using** close()** operation. After closing a file, if you want to do any other operation on it, it will fail. We can check if a file is closed or not properly using “file_name.closed” method. It returns True if it is closed.
The best way to perform file operations in python is by using “with” keyword :
with open(“myfile.txt”,’r’) as f:
# do file operations
It will close the file automatically, even if an exception is raised.
with open("myfile.txt",'r') as f:
# do file operations
f = open("myfile.txt","w")
print f.closed
print f.closed
If you will run the above function, first will print “False” and the second print will print “True”
Writing to a file in python :
So, we have checked how to open and close a file, now let’s check how to write data to a file . For writing , we use “file.write(string)” . It will write content of “string” to the file “file” and returns none.
Let’s modify the above program to write something to a file :
with open("myfile.txt",'w') as f:
f.write("Hello World !!")
Now open the file** “myfile.txt”** and it should contain** “Hello World !!**” line.
Change it to the following :
with open("myfile.txt",'w') as f:
f.write("Hello World !!")
with open("myfile.txt",'w') as f:
f.write("Hello World again !!")
Run and open the file : it will contain** “Hello World again !!”** only . Why ? Since we have opened the file using** “w”** mode, it will overlap everything.
Append in a file :
In the above example, after writing to a file for the second time, it replaces the words . To append more letters to a file, we should use append file mode ( “a”) .
Your “myfile.txt” file already has** “Hello World again !!”** . Now , let’s try to add some more words to this line. Change the .py file as below :
with open("myfile.txt",'a') as f:
f.write("Hello World !!")
fun this file and check the “myfile.txt” : It will contain the following text :
"Hello World again !!Hello World !!"
Reading contents of a file :
We have learnt how to open , close, write and append to file in python. Let’s take a look :
First change “myfile.txt” as below :
Line One
Line Two
Line Three
Now we will read these lines : Change the python file as below :
with open("myfile.txt",'r') as f:
print f.read()
It will print all the three lines. We can also pass an argument to the read() function , to indicate how many characters we need to read :
with open("myfile.txt",'r') as f:
print f.read(7)
It will print “Line On”
We can also use “readline” and “readlines” methods to read lines :
“readline” prints the first line :
with open("myfile.txt",'r') as f:
print f.readline()
Output : “Line one”
“readlines” reads all the lines :
with open("myfile.txt",'r') as f:
print f.readlines()
Output : [‘Line One\n’, ‘Line Two\n’, ‘Line Three’]