Updated: May 18, 2020
File is a named location on disk to store related information. It is used to permanently store data in a non-volatile memory. Firstly we open the file for read and write to a file after it we need to be closed files. There are following order for a file operation in Python.
· Open a file
· Read operation
· Write operation
· Close the file
How to open a file?
We use a built-in function open() to open a file. This function creates a file object, also called a handle, as it is used to read or modify the file accordingly.
f = open("test.txt") # open file in current directory
f = open("C:/Python33/README.txt") # specifying full path
We can identify the mode while opening a file. In mode, we specify whether we want to read 'r', write 'w' or append 'a' to the file. We also specify if we want to open the file in text mode or binary mode.
Python File Modes
'r' Open a file for reading. (default)
'w' Open a file for writing. Creates a new file if it does not exist or truncates the file if it exists.
'x' Open a file for exclusive creation. If the file already exists, the operation fails.
'a' Open for appending at the end of the file without truncating it. Creates a new file if it does not exist.
't' Open in text mode. (default)
'b' Open in binary mode.
'+' Open a file for updating (reading and writing)
f = open("test.txt") # equivalent to 'r' or 'rt'
f = open("test.txt",'w') # write in text mode
f = open("img.bmp",'r+b') # read and write in binary mode
f = open("test.txt",mode = 'r',encoding = 'utf-8') #files text mode
How to close a file Using Python?
After complete all operations to the file, we need to close the file and we use close () for Closing a file.
f = open("test.txt",encoding = 'utf-8')
# perform file operations
How to write to File Using Python?
In order to write into a file in Python, we need to open it in write 'w', append 'a' or exclusive creation 'x' mode. We require to be careful with the 'w' mode as it will overwrite into the file if it already exists. All previous data are erased. Writing a string or sequence of bytes is done using write() method. This method returns the number of characters written to the file.
with open("test.txt",'w',encoding = 'utf-8') as f:
f.write("my first file\n")
f.write("contains three lines\n")
This program will create a new file named 'test.txt' if it does not exist. If it does exist, it is overwritten.
How to read files in Python?
In Python we use read () to read a file but we must open the file in reading mode. We can use the read (size) method to read in size number of data. If size parameter is not specified, it reads and returns up to the end of the file.
f = open("test.txt",'r',encoding = 'utf-8')
f.read(4) # read the first 4 data
f.read(4) # read the next 4 data
f.read() # read in the rest till end of file
'my first file\nThis file\ncontains three lines\n'
f.read() # further reading returns empty sting