File handling is an important component of any application.
Python has multiple functions for creating, reading, updating, and deleting files. In Python, the
open() function is used to work with files.
open() function takes two parameters;
In mode, we specify whether we want to read
w or append
a to the file. We can also define if we want to open the file in text mode or binary mode.
In Python, file handling operation occurs in the following order:
- Open a file using
- Perform the operation (read or write).
- Close the file using
There are different methods (modes) for opening a file:
||Read||Opens a file for reading, returns an error if the file does not exist. It is a default mode.|
||Write||Opens a file for writing a file, creates the file if it does not exist or deletes the content of the file if it exists.|
||Append||Opens a file for appending at the end of the file without deleting the content of it, creates the file if it does not exist|
||Create||Creates the specified file, returns an error if the file exists|
||Text mode||Opens a file in text mode. It is a default mode.|
||Binary mode||Opens a file in binary mode.|
||Update||Opens a file for updating i.e. reading and writing.|
Reading a file is enough to specify the name of the file.
f = open("file_name.txt") # open a file in current directory f = open("C:/Python/file_name.txt") # define full path f = open("file_name.txt") # identical to 'r' or 'rt' f = open("file_name.txt",'w') # write in text mode f = open("image_file.bmp",'r+b') # read and write in binary mode f.close()
The best way to close a file is by using the with statement. This ensures that the file is closed when it exit and it avoids the runtime exception.
Reading Files in Python
In order to read a file in Python, we must open the file in reading
The following methods are useful while reading a file:
Read data from specified size i.e. number of lines. If the
>>> f.read(4) # read the first 4 data
We can change the file cursor (position) using
>>> f.tell() # returns the current file position
>>> f.seek(0) # set file cursor to initial position
Read one line of the file:
f = open("test.txt") print(f.readline())
Read all lines of the file:
with open("test.txt", 'rt') as f: print(f.readline())
Writing to Files in Python
In order to write a file in Python, we need to open it in write
a or creation
We need to be concerned with the write
w mode, as it will overwrite into the file if it already exists. Due to this, all the previous data are deleted.
Open the file “test.txt” and append content to the file:
f = open("test.txt", 'a') f.write("Hello world!") f.close()
Open the file “text.txt” using
with open("test.txt, 'w') as f: f.write("my first linen") f.write("this is second linenn") f.write("this is third linen")
In the above example, write
w mode will overwrite the contents of
Deleting files in Python
In order to delete a file, you must import the OS module, and run its
import os if os.path.exists("text.txt"): os.remove("text.txt") else: print("The file does not exists")
In the above example,
os.path.exists() method is used to check whether the file exists or not. If exists it will remove using
os.remove() method. Otherwise, it will return file does not exist.