File Handling in Python
File Handling in Python
File handling in Python involves working with files – mainly opening them, reading from and writing into them and then closing them. There are several other operations that are done or can be done in between which will be explained later in this post.
Open File
To open a file in Python, open() function is used and it is returned as a file object to the script that called the function. It takes filename and mode as parameters and syntax of open() function is given below:
Syntax of open() function:
open(filename, mode)
Parameters of open() function:
Parameters | Description |
filename | Required. Name of the file along with the path is specified which need to be opened. |
mode | Optional. The purpose of opening the file is specified through this parameter and default is read mode for text file which is “r”. |
The different modes of opening a Python file are given below:
Mode | Description |
r | Default value. This mode opens a file for reading only and raises an exception if the file does not exist. |
r+ | This mode opens a file for reading and writing and raises an exception if the file does not exist. |
w | This mode opens a file for writing only and creates the file if it does not exist. |
w+ | This mode opens a file for reading and writing and creates the file if it does not exist. |
a | This mode opens a file for appending only and creates the file if it does not exist. |
a+ | This mode opens a file for appending and reading and creates the file if it does not exist. |
x | This mode creates the specified file and raises an exception if the file already exists. |
x+ | This mode creates the specified file and opens the file in reading and writing mode. It raises an exception if the file already exists. |
Apart from the modes mentioned above, two other modes can be used to open a file in either text or binary mode and they are given below:
Mode | Description |
t | Default value. This mode opens a file in the text mode. |
b | This mode opens a file in the binary mode. |
File Handling in Python Example – open() function
# Python program to exemplify opening a file # First way myFile=open("08-30-16-TMSD-5th-truncated.txt","r") # or # Second way myFile=open("08-30-16-TMSD-5th-truncated.txt")
Read File
To read a Python file, read() method of the file object can be used.
File Handling in Python Example – read() method
# Python program to exemplify read() method # Opening python_example.txt in default mode -> r mode myFile=open("python_example.txt") # reading and then printing the contents of the file opened above print(myFile.read())
The output provided below is the content of the file opened above.
Output:
Welcome to StudyExperts! This is a dummy file.
Read a part of File
To read a part of Python file, read() method of the file object can be used to read few bytes of the file. Number of bytes to be read need to be specified as an argument of the method.
File Handling in Python Example – read() method
# Python program to exemplify read() method # Opening python_example.txt in default mode -> r mode myFile=open("python_example.txt") # reading and then printing the first 15 bytes of the file opened above print(myFile.read(15))
Output:
Welcome to Stud
Read Lines
To read a line of Python file, readline() method is used of the file object.
File Handling in Python Example – readline() method
# Python program to exemplify readline() method # Opening python_example.txt in default mode -> r mode myFile=open("python_example.txt") # reading and then printing the first line of the file opened above print(myFile.readline())
Output:
Welcome to StudyExperts!
Loop through the Lines of the File
To read a Python file line by line for and while loop can be used, though while loop requires readline() method invocation whereas for loop does not.
File Handling in Python Example – for loop to read line by line
# Python program to exemplify for loop to read line by line # Opening python_example.txt in default mode -> r mode myFile=open("python_example.txt") # for loop to read Python file line by line for line in myFile: print(line)
Output:
Welcome to StudyExperts! This is a dummy file.
File Handling in Python Example – while loop to read line by line
# Python program to exemplify while loop to read line by line # Opening python_example.txt in default mode -> r mode myFile=open("python_example.txt") # reading and then printing the first line of the file opened above line=myFile.readline() # while loop to read Python file line by line while line: print(line) line=myFile.readline()
Output:
Welcome to StudyExperts! This is a dummy file.
Close File
To close a Python file, close() method of the file object is used. It used to close the opened file.
File Handling in Python Example – close() method
# Python program to exemplify close() method # Opening python_example.txt in default mode -> r mode myFile=open("python_example.txt") # reading and then printing the contents of the file opened above print(myFile.read()) # closing the file opened above myFile.close()
Output:
Welcome to StudyExperts! This is a dummy file.
Writing to an Existing File
Python file object has a write() method to write into a file, but to actually write into it, it should be opened in one of the two writing modes which are “a” – to append content at the end of the file and “w” – to overwrite the already existing content of file if it has any.
File Handling in Python Example – write() method
# Python program to exemplify write() method # Opening python_example.txt in append mode -> a mode myFile=open("python_example.txt", "a") # writing into the file opened above myFile.write("Adding more content in python_example.txt file") # closing the file opened above myFile.close() # Opening python_example.txt in overwrite mode -> w mode myFile=open("python_example.txt", "w") # writing into the file opened above myFile.write("Overwriting content in python_example.txt file") # closing the file opened above myFile.close()
Delete File
To delete a Python file, remove() function of “os” module is used. So, to be able to use it, the module first has to be imported in the current script.
File Handling in Python Example – deleting a file
# Python program to exemplify deleting a file import os os.remove("python_example.txt")
Check if File Exist
To check is the file exists, path.exists() function of “os” module is used. So, to be able to use it, the module first has to be imported in the current script.
File Handling in Python Example – checking if a file exists
# Python program to exemplify how to check if a file exists import os if os.path.exists("python_example.txt"): os.remove("python_example.txt") else: print("python_example.txt does not exist")
Delete Folder
To delete a folder, mkdir() function of “os” module is used. So, to be able to use it, the module first has to be imported in the current script.
File Handling in Python Example – deleting a folder
# Python program to exemplify deleting a folder import os os.rmdir("myFolder")