Introduction
Like other programming languages, Python also provides a feature for working with text and binary files. This is much easier to do with Python than with other languages.
In this tutorial, you will learn File Handling in Python and all the operations that come under this topic. For example, storing data into a file, reading data from a file, appending data into a file, and many more.
We will cover this topic with various programming examples. So, without wasting any more time let's get straight to the main topic.
How to open a file in Python?
First, we will begin our today's lesson by learning how to open a file. Here, the open() method is gonna help us. It's a built-in method in python. There is another way to open a file but we will discuss it later. You have to use the following modes to open a file.
Types of modes used to open a file
Mode | Description |
---|---|
'r' | Read a file |
'w' | Write to a file |
'a' | Append to a file(It refers to insert at the end of the file) |
'rb' | Reading in binary mode |
'r+' | To read and write both |
'rb+' | Reading and writing in binary |
'w+' | Write and Read both |
'wb' | Write in binary mode |
'a+' | Append and read both(file pointer points to the end of the file) |
'ab' | Append in binary mode |
'ab+' | Append and read in binary mode |
Sample File
Look at the text below. Throughout this tutorial, I will use this text file to show you the examples.
file.txt
Employee Name: David Brown
Employee ID: 500891
Employee Age: 42
Blood Group: A+
Address: 4293 Hill Street, Convoy, Ohio, 12345, United States
Contact: +11234567890
Email: davidbro@gmail.com
Open a file in python
There are two methods to open a file in python. Let's see one after one.
Method 1: using "open()" method
The method is too simple here. You just need to mention the filename and the opening mode in the open() method.
# open the file with read mode
f = open('file.txt', 'r')
# print the filename
print(f"The Filename is: {f.name}\n")
# closing the file
f.close()
Output
The Filename is: file.txt
Method 2: using "with open()" method
This is a more convenient way to open a file in Python. In this case, we don't need to close the file once it's opened.
with open('file.txt') as f:
print("-----The data-----")
print(f.read())
# check the file has closed or not
# return bool value
print(f"\nIs closed? {f.closed}")
Output
-----The data-----
Employee Name: David Brown
Employee ID: 500891
Employee Age: 42
Blood Group: A+
Address: 4293 Hill Street, Convoy, Ohio, 12345, United States
Contact: +11234567890
Email: davidbro@gmail.com
Is closed? True
How to read a file in Python?
There are several built-in methods to read a file in python. We'll cover all of them one by one.
Read the entire data using the "read()" method
with open('file.txt', 'r') as f:
# Read the entire data
# print the file name
print(f.name, "\n")
print(f.read())
Output
file.txt
Employee Name: David Brown
Employee ID: 500891
Employee Age: 42
Blood Group: A+
Address: 4293 Hill Street, Convoy, Ohio, 12345, United States
Contact: +11234567890
Email: davidbro@gmail.com
Read a file line by line using a for loop
This is a tricky method and is not used very often. The below example is for you.
'''read data from a file using for loop'''
f = open('file.txt', 'r')
print("file.txt\n")
for line in f:
print(line, end='')
f.close()
Output
file.txt
Employee Name: David Brown
Employee ID: 500891
Employee Age: 42
Blood Group: A+
Address: 4293 Hill Street, Convoy, Ohio, 12345, United States
Contact: +11234567890
Email: davidbro@gmail.com
Read a Single line from a file using the "readline()" method
The readline() method is used to read only a single line from a file. The below code is an example of it.
# Read only one line from a file
with open('file.txt', 'r') as f:
print(f.readline())
Output
Employee Name: David Brown
"readlines()" method in python
readlines() method returns a list containing all the lines in the file as an item. So, you can use this method to read multiple lines from a file.
with open('file.txt', 'r') as f:
print(f.readlines())
Output
['Employee Name: David Brown\n', 'Employee ID: 500891\n', 'Employee Age: 42\n', 'Blood Group: A+\n', 'Address: 4293 Hill Street, Convoy, Ohio, 12345, United States\n', 'Contact: +11234567890\n', 'Email: davidbro@gmail.com']
Printing file data like the above format is not a good idea because it's in compact form. So, we need to make it human-readable. The below code will help you.
with open('file.txt', 'r') as f:
for line in f.readlines():
print(line, end='')
print("\n")
Output
Employee Name: David Brown
Employee ID: 500891
Employee Age: 42
Blood Group: A+
Address: 4293 Hill Street, Convoy, Ohio, 12345, United States
Contact: +11234567890
Email: davidbro@gmail.com
Read only specific lines from a file
Suppose, you need to print only the first two lines from a file instead of the rest. To accomplish this task, we will use the readlines() method and a Python list technique (see the yellow line).
with open('file.txt', 'r') as f:
print("----Printing the first two lines----\n")
for line in f.readlines()[:2]:
print(line, end='')
Output
----Printing the first two lines----
Employee Name: David Brown
Employee ID: 500891
How to Add data to a file in python?
There are two methods to add data to a file, the write() and append() methods. Let us first see the difference between these two methods.
Append vs Write function
Both functions are used to perform write operations but the major difference is, the append function appends the new data at the end of a file without changing the existing data. See the below example to know it better.
In this case, we'll append the 'Height' of the employee to the file.txt file without changing the existing data.
# opening the file in the append mode
with open('file.txt', 'a+') as f:
f.write("\nHeight: 5'9”")
# setting the pointer at the 0th position(beginning)
f.seek(0)
print(f.read())
Output
Employee Name: David Brown
Employee ID: 500891
Employee Age: 42
Blood Group: A+
Address: 4293 Hill Street, Convoy, Ohio, 12345, United States
Contact: +11234567890
Height: 5'9”
Write to a file in python
The write() method is very similar to the append() function but, in this case, the entire data in a file is overwritten by the new data.
with open('file.txt', 'w+') as f:
f.write("David has left the job.")
# set the cursor at the 0th position
f.seek(0)
print(f.read())
Output
David has left the job.
seek function in python
In File Handling in Python, the seek() function is used to set the current position of the cursor from which new data can be inserted. We have already used this in the previous example (see the yellow line). There we set the cursor to the 0th position but here, we will set the cursor to the end.
Code
# Opening the file in the append and read mode
with open('file.txt', 'a+') as f:
length = len(f.read())
# set the cursor position at the end
f.seek(length)
f.write(" So, Julia is missing him too much")
# again set the cursor
f.seek(length)
print(f.read())
Output
David has left the job. So, Julia is missing him too much
Summary
In this tutorial, we covered a very important topic which is File Handling in Python. We performed various programming examples here to learn the topic better.
Topics we covered here: opening a file, reading data from a file, writing and append operations, seek() function, etc. If you have any queries related to this topic, please leave your comment below, you will get an immediate response.
Thanks for reading!💙
PySeek