In this blog, you will learn about File Handling in Python. Don’t worry I have explained the File Handling in Python concept in a very detailed manner. File Handling in Python provides various operations that we can perform on the files. All the methods related to files explain with the program. So let’s get started with the blog.
Introduction to File Handling in Python
Before learning about File Handling in Python, we should know about the File. Sometimes the data which we want to display may be very large, and only a line console since the memory is volatile, it is impossible to recover the programmatically generated data again and again.
Here, the File plays an important role when the data needs to be stored permanently in the file. A file is a named location that accesses the stored information (non-volatile) after the program termination.
Compared with other programming languages the file handling implementation is quite difficult but in python, it is easier and shorter.
In Python, files are treated in two modes as text or binary. Each line of a file ends with a distinctive character, whether the file is in text or binary format.
A text file is created by the character sequences in each line of code. Each line of a file is terminated by an exclusive character known as the EOL or End of Line character, such as the comma () or newline character. It signals to the interpreter that the current line must end and that a new one must start.
Hence, a file operation can be done in the following order.
- Open a file.
- Read or write – performing operations.
- Close the file.
Operations on Files of File Handling in Python
Before reading and writing any data into a file, it is important to learn how to open and close a file.
Opening File: Unless you open a file, you can not write anything in a file or read anything from it.
Closing File: Once you are done with reading or writing, you should close the file.
a) Opening a File
Before performing any operations on the file like reading or writing, first we have to open that file. To do this, we should use the built-in Python function open(), but we must first give the mode, which denotes the goal of the opening file.
Syntax:
# Opening the file
f = open(filename,mode)
Python provides an open() function that accepts two arguments, i.e; file name and access mode in which the file is accessed. It returns a file object which can be used to perform various operations like reading, writing, etc.
Files can be accessed using various modes like read, write, or append. The following are the details about the access mode to open a file.
Sr | Access Mode | Description |
1 | r | Opens the file for read-only mode. The file pointer exists at the beginning. By default, the file is open in this mode if no access mode is passed. |
2 | rb | Opens the file to read-only in binary format. In the file, the file pointer exists at the beginning. |
3 | r+ | Open the file to read and write at the same time. The file pointer exists at the beginning of the file. |
4 | rb+ | Open the file to read and write at the same time in binary format. The file pointer exists at the beginning of the file. |
5 | w | Open the file to write only. If the file is not present then it will create a new file with the same name. If the file is present then it will overwrite that file. The file pointer exists at the beginning of the file. |
6 | wb | Open the file to write only in binary format. If the file is not present then it will create a new file with the same name. If the file is present then it will overwrite that file. The file pointer exists at the beginning of the file. |
7 | w+ | Open the file to write and read at the same time. It is different from r+ in the sense, if the file is not present then it will create a new file with the same name. If the file is present then it will overwrite that file. The file pointer exists at the beginning of the file. |
8 | wb+ | Open the file to write and read at the same time in binary format. It is different from r+ in the sense, if the file is not present then it will create a new file with the same name. If the file is present then it will overwrite that file. The file pointer exists at the beginning of the file. |
9 | a | Opens the file in the append mode. If the file is not present then it will create a new file with the same name, otherwise, the file pointer exists previously written at the end so we can append new content where we have left off. |
10 | ab | Opens the file in the append mode in binary format. If the file is not present then it will create a new file with the same name, otherwise, the file pointer exists previously written at the end so we can append new content where we have left off. |
11 | a+ | Opens the file in the append and read mode. If the file is not present then it will create a new file with the same name, otherwise, the file pointer exists previously written at the end so we can append new content where we have left off. |
12 | ab+ | Opens the file in the append and read mode in binary format. If the file is not present then it will create a new file with the same name, otherwise, the file pointer exists previously written at the end so we can append new content where we have left off. |
Let us see some examples, so we can easily understand what we have read now.
Suppose I have created a file name binfin_details.text and written some contents in that.
binfin_details.text
Employee List of BinFin Tech
Alex
Sam
Travis
Copper
Maverick
Dominic
Now let’s open the file with the help of Python code.
fs = open('./binfin_details.txt', 'r')
if fs:
print("File Opened Successfully")
print(fs)
# Output:
File Opened Successfully
<_io.TextIOWrapper name='./binfin_details.txt' mode='r' encoding='UTF-8'>
As we know, open() functions return the object of the file. Therefore it successfully satisfies the if condition and prints the next statement.
The other output is the object returned by the open().
b) Closing the file
Once we have completed all the operations on the file, we must close it. Python provides a built-in function that is close(), which is used to close the file.
Suppose if we don’t close the file we can perform any external operation on it, so for safety purposes, we must close the file if we have completed the operations on that file.
Syntax:
fs = open('./binfin_details.txt', 'r')
if fs:
print("File Opened Successfully")
# Closing the file
fs.close()
In this way, we close the file. But here comes a problem if the error is not handled properly in the program we cannot close the file properly. To avoid such a problem we should always keep the close part in the final block. So even if the error occurs we can properly close the file.
try:
fs = open('./binfin_details.txt', 'r')
if fs:
print("File Open successfully")
finally:
fs.close()
print("File Closed Successfully")
## Output:
File Open successfully
File Closed Successfully
After entering the try block, it goes to the finally block. Even if the error occurs in the try block, it will execute the finally block. In that way, the file will be closed properly.
c) Writing the Content in the File
To write some content in the file, first of all, we have to open the file and write some content in it. There are two modes from which we can write content in the file.
- w: In these, the file pointer is at the beginning of the file. If the file is present then it will overwrite the file otherwise it will create a new file.
- a: In these, the file pointer is at the end of the file. If new content is added it will start at the end of the file. If the file is present then it will overwrite the file otherwise it will create a new file.
Suppose I have created a file name binfin_details.text and written some contents in that.
Employee List of BinFin Tech
Alex
Sam
Travis
Copper
Maverick
Dominic
Now, I have to write the content at the beginning of the file.
# Write the file with access mode w
try:
fs = open("./binfin_details.txt", 'w')
if fs:
fs.write("Thanks for joining our company")
finally:
fs.close()
Output:Thanks for joining our company
In this, we can clearly see that it deleted all the previous content and add new content from the start of the file.
Now, Let’s see the example of writing the content in the file with access mode a.
try:
fs = open("./binfin_details.txt", 'a')
if fs:
fs.write("Congrats all the newly joined Employee.")
finally:
fs.close()
Output:
Employee List of BinFin Tech
Alex
Sam
Travis
Copper
Maverick
DominicCongrats all the newly joined Employee.
In this we can clearly see that the previous content of the file is not deleted, but also added the content at the end of the file. The basic difference between w and a is that w deletes all the previous content and adds the new content from the beginning of the file while a adds the new content at the end of the file storing the previous content of the file.
d) Read the content of the file.
To read the content of the file, Python provides a built-in function called read(). The read() method reads a string from the file. It can read the data in the text as well as in binary format.
Syntax:
fileobj.read(<count>)
Here, the count is the number of bytes to be read from the file starting file. If the count argument is not passed then it will read the content of the file until the end.
# Read the content of the file
try:
fs = open('./binfin_details.txt', 'r')
content = fs.read(20)
print("Type of the string: ", type(content))
print("Read the file with bytes ", content)
finally:
fs.close()
## Output:
Type of the string: <class 'str'>
Read the file with bytes Employee List of Bin
e) Read file through for loop
We can read the file with help of using loop
try:
fs = open('./binfin_details.txt', 'r')
for i in fs:
print(i)
finally:
fs.close()
## Output:
Employee List of BinFin Tech
Alex
Sam
Travis
Copper
Maverick
DominicCongrats all the newly joined Employee.
f) Read Lines of the File
Read the content of the file line by line by using a function readline() method. readline() reads the lines of the file from the beginning i.e if we use the readline() method 4 times it will read 4 lines of the file.
try:
fs = open('./binfin_details.txt', 'r')
line1 = fs.readline()
line2 = fs.readline()
print(line1)
print(line2)
finally:
fs.close()
## Output:
Employee List of BinFin Tech
Alex
Python provides a built-in function called readlines() which is also used the read the content of the file. But the difference is that it returns the list of the lines till the end of the file is reached.
try:
fs = open('./binfin_details.txt', 'r')
line_list = fs.readlines()
print(line_list)
finally:
fs.close()
## Output:
['Employee List of BinFin Tech\n',
'Alex\n', 'Sam\n', 'Travis\n', 'Copper\n',
'Maverick\n',
'Dominic.Congrats all the newly joined Employee.']
It returns each index as a single index in the list.
g) Creating a new File
We can create new files in Python. Python provides a built-in function to create new files with the help of the open() function. Firstly, we used the open function for opening the file. But if you want to create the file you have to pass access mode with open()
a) x: It creates a new file with the specified name. It causes an error when the file exists with the same name.
b) a: If the file is not present it creates a new file with the same name. If it is present then append the content of the existing file.
c) w: If the file is not present it creates a new file with the same name. If it is present it overwrites the existing file.
fs = open('./new_file.txt', 'x')
print(fs)
if fs:
print("File Created Successfully")
## Output:
<_io.TextIOWrapper name='./new_file.txt' mode='x' encoding='UTF-8'>
File Created Successfully
h) File Pointer Positions
Python provides the built-in function which is used to print the byte number at which the file pointer currently exists.
try:
fs = open('./binfin_details.txt', 'r')
print("Inital pointer position bytes :", fs.tell())
fs.read()
print("Final Pointer position bytes :", fs.tell())
finally:
fs.close()
## Output:
Inital pointer position bytes : 0
Final Pointer position bytes : 108
From the above code, we can conclude that the reading of the file starts from the beginning of the file which is why we get 0 bytes and after reading all the content of the file we get 108 bytes, which is now the current file pointer position.
i) Modifying the File Pointer Position
Since we might need to read or write the content at different locations in real-world applications, we occasionally need to alter the file pointer location externally.
Python offers us the seek() function, which allows us to externally change the file pointer location, for this purpose.
The seek() method’s syntax is provided below.
Syntax:
<file-ptr>.seek(offset[, from)
seek() method accepts two parameters:
offset: Refers to the new position of the file pointer within the file.
from: It indicates the reference position from where the bytes are to be moved. The file’s beginning is utilized as the reference position if it is set to 0. When it is set to 1, the file pointer’s current position serves as the reference position. If it is set to 2, the reference position is the file’s end pointer.
try:
fs = open('./binfin_details.txt', 'r')
print("Inital pointer position bytes :", fs.tell())
fs.seek(5)
print("Final Pointer position bytes :", fs.tell())
finally:
fs.close()
## Output:
Inital pointer position bytes : 0
Final Pointer position bytes : 5
Conclusion
File Handling in Python enables users to read and write files as well as perform a variety of other operations on files. Like many other concepts in Python, the idea of file management has been extended to a number of other languages, but their implementations are either difficult or time-consuming. Python handles text and binary files differently, and this is crucial.
FAQ
Before learning about File Handling in Python, we should know about the File. Sometimes the data which we want to display may be very large, and only a line console since the memory is volatile, it is impossible to recover the programmatically generated data again and again.
Here, the File plays an important role when the data needs to be stored permanently in the file. A file is a named location that accesses the stored information (non-volatile) after the program termination.
In Python, files are treated in two types of files: text or binary.
Each line of a file ends with a distinctive character, whether the file is in text or binary format.
A text file is created by the character sequences in each line of code.
Each line of a file is terminated by an exclusive character known as the EOL or End of Line character, such as the comma () or newline character. It signals to the interpreter that the current line must end and that a new one must start.
Sometimes the data which we want to display may be very large, and only a line console since the memory is volatile, it is impossible to recover the programmatically generated data again and again.
Read the content of the file line by line by using a function readline() method. readline() reads the lines of the file from the beginning i.e if we use the readline() method 4 times it will read 4 lines of the file.
File handling in Python has three modes that are read, write and append.