File Handling in Python
OBJECTIVES
Files are an important part of any computer. We might be accessing a lot of files on a day to day basis. In this
chapter we will discuss files and how we can operate on files with Python.
WHAT IS A FILE
A file is a place where we save some data or contents. We write the data and programs to a file and we can read
from that file.
Generally, files are classified into two i.e.,
1. text files : .txt , .docx etc.
2. binary files : .mp4 , . jpeg etc.
Text files are simple and easy to read as they are in human-readable format, whereas binary files contain binary
data which is understood only by computers.
Files can be stored on various storage devices like hard drives or optical drives.
A filename consists of two parts: name and a suffix called file extension.
The user can identify the type of file, file format etc., from the file extension. The type of file is given by its
extension. For example , a doc file has a file extension .docx.
When we are reading and writing using Python, we first need to open the file. Once the reading or writing is done,
we have to close the file. The order of file execution is:
1. Open the file
2. Read or write operation
3. Close the file
CREATING AND OPENING A FILE
For any file operation, the first thing is to open the file. Python has a built-in function open() to perform this
operation.
This function returns a file object called the file handler, which can be used to do further operations.
Syntax : file_object = open(“file_name” , “mode”)
Here the open() function accepts two arguments- one the file_name which can also be the complete path location
of the file.
The other is an optional parameter mode, which defines for what purpose we want to open the file, i.e., read, write,
append, etc.
The default value for mode is reading.
Text File - example.txt
HELLO !!
ARE YOU THERE ??
Code :
file1=open("C:/Users/hp/OneDrive/Desktop/PYTHON/File/example.txt")
print(file1)
Output :
<_io.TextIOWrapper name='C:/Users/hp/OneDrive/Desktop/PYTHON/File/example.txt' mode='r'
encoding='cp1252'>
The output provides the following details:
Name:'C:/Users/hp/OneDrive/Desktop/PYTHON/File/example.txt' (the path to the file)
Mode: 'r' (the file is opened in read mode)
encoding: 'cp1252' (the encoding used for the file)
Summary:
The open function opens the specified file and returns a file object.
The print(file1) statement prints information about the file object, including its path, mode, and encoding.
This code ensures that the file is successfully opened and ready for reading.
LIST OF DIFFERENT MODES FOR OPENING THE FILE
MODES DESCRIPTION
r Open the file in read-only mode. This is the default mode. The file pointer will be placed at the start
of the file.
rb It opens the file only in binary format and in read-only mode. The file pointer will be placed at the
start of the file.
r+ Opens the file for both reading and writing. The file pointer will be placed at the start of the file.
rb+ Opens the file for both reading and writing in binary format. The file pointer will be placed at the
start of the file.
w It opens the file in write-only mode. If a file exists, it will be overwritten. If the file does not exist
then it will create a new file.
wb It opens the file for writing mode in binary format. If a file exists, it will be overwritten. If the file
does not exist then it will create a new file.
w+ It opens the file for both reading and writing. If a file exists, it will be overwritten.
If the file does not exist then it will create a new file.
wb+ It opens the file for both reading and writing in binary format. If a file exists, it will be overwritten.
If the file does not exist then it will create a new file.
a It opens the file for appending. The file pointer is placed at the end of the file. It will create a new
file for writing in case the file does not exist.
ab It opens the file for appending in binary format. The file pointer is placed at the end of the file. It
will create a new file for writing in case the file does not exist.
a+ It opens the file for appending and reading. The file pointer is placed at the end of the file. It will
create a new file for writing in case the file does not exist.
ab+ It opens the file for appending and reading in binary format. The file pointer is placed at the end of
the file. It will create a new file for writing in case the file
does not exist.
x It creates a new file. If the file already exists, then the operation fails rather than overwriting.
Table shows all the modes available in Python for the open() function. We can always specify whether we
want to open the file in text mode or in binary mode. By default, Python always opens the file for reading in
text mode.
Code :
file1=open("C:/Users/hp/OneDrive/Desktop/PYTHON/File/example.txt","rb")
print(file1)
Output :
<_io.BufferedReader name='C:/Users/hp/OneDrive/Desktop/PYTHON/File/example.txt'>
Breakdown of the Code:
1. file1 = open("C:/Users/hp/OneDrive/Desktop/PYTHON/File/example.txt", "rb"):
The open function is used to open the file located at
"C:/Users/hp/OneDrive/Desktop/PYTHON/File/example.txt".
The "rb" mode specifies that the file should be opened in binary read mode.
The variable file1 is assigned the file object returned by open.
2. print(file1):
This prints the file object, which includes its type and name.
The output <io.BufferedReader name='C:/Users/hp/OneDrive/Desktop/PYTHON/File/example.txt'>
indicates that file1 is a buffered reader object associated with the specified file.
Detailed Explanation:
● File Opening in Binary Read Mode:
The "rb" mode is used for reading the file in binary format. This is typically used for non-text files like
images, PDFs, etc.
In this case, even though the file is a .txt file, it is opened in binary mode, meaning the file's raw binary
content can be read.
● File Object:
The file1 variable holds a reference to a file object created by the open function.
When you print a file object, Python provides a representation of the file object. This includes the type of
the file object (<io.BufferedReader> in this case) and the path of the file
(name='C:/Users/hp/OneDrive/Desktop/PYTHON/File/example.txt').
READING AND CLOSING A FILE
Reading
SYNTAX : filename.read()
Closing
SYNTAX : filename.close()
Code : Read and Close a file
file1=open("C:/Users/hp/OneDrive/Desktop/PYTHON/File/example.txt")
file_content=file1.read()
print(file_content)
print(type(file_content))
file1.close()
Output :
HELLO !!
ARE YOU THERE ??
<class 'str'>
The most commonly used method or the best approach of doing the file operation is with the 'with' keyword. This
is because, when an operation is done with the 'with' keyword and once it exits from the 'with' block it will close the
file automatically and will destroy the file object automatically and thus save us from taking extra precaution to
close the file.
SYNTAX : with open (file , mode) as file_obj :
step_1
step_2
step_3
.
.
step_N
Code :
with open("C:/Users/hp/OneDrive/Desktop/PYTHON/File/example.txt") as f:
print(f.read())
Output :
HELLO !!
ARE YOU THERE ??
FILE OBJECT ATTRIBUTES
When any file is opened using the open() function, it creates a file object which can be called a file handler. Using
this we can get a lot of information about that file. There are three main attributes which we will be discussing one
by one here below.
1. name
It will return the name of the file.
Syntax: file_obj.name
2. closed
It returns a Boolean value. If the file is closed it will return true, otherwise, it will return false.
Syntax: file_obj.closed
3. mode
It returns the access mode by which the file is opened.
Syntax: file_obj.mode
Code : File object attributes
file1=open("C:/Users/hp/OneDrive/Desktop/PYTHON/File/example.txt")
print(file1.name)
print(file1.closed)
print(file1.mode)
file1.close()
Output :
C:/Users/hp/OneDrive/Desktop/PYTHON/File/example.txt
False
r
READING FROM A FILE
Once we open a file, we can do a number of file operations. Let us see how we can perform the read operation. In
order to read from a file, first we need to open the file in reading(r) mode. There are a number of methods with
which we can read from a file. We will be discussing a few of the methods here.
1. read()
We can use the read() method to read the file from start to end. The read() method also accepts a parameter size
with which we can specify the number of bytes that we need to read.
Syntax: file_obj.read(size)
Code :
file1=open("C:/Users/hp/OneDrive/Desktop/PYTHON/File/example.txt","r")
file_content=file1.read()
print(file_content)
file1.close()
Output :
HELLO !!
ARE YOU THERE ??
Code :
file1=open("C:/Users/hp/OneDrive/Desktop/PYTHON/File/example.txt","r")
file_contentsize=file1.read(5)
print(file_contentsize)
file1.close()
Output :
HELLO
2. readline() and readlines()
We can read from the file using the readline() and readlines() function as well.
The readline() is a method of reading a file line by line.
Whenever we use readliness() it reads line by line till the end of the file.
Syntax : file_obj.readline()
Code :
file1=open("C:/Users/hp/OneDrive/Desktop/PYTHON/File/example.txt","r")
line1=file1.readline()
print(line1)
line2=file1.readline()
print(line2)
file1.close()
Output :
HELLO !!
ARE YOU THERE ??
Code :
file1=open("C:/Users/hp/OneDrive/Desktop/PYTHON/File/example.txt","r")
line1=file1.readline()
print(line1)
line2=file1.readline()
print(line2)
line3=file1.readline()
print(line3)
file1.close()
Output :
HELLO !!
ARE YOU THERE ??
readlines()
Syntax : file_obj.readlines()
Code :
file1=open("C:/Users/hp/OneDrive/Desktop/PYTHON/File/example.txt","r")
data=file1.readlines()
print(data)
file1.close()
Output :
['HELLO !!\n', 'ARE YOU THERE ??']
We can read line by line using the readlines() function as well, wherein readlines() will return all the lines of
the file as a list.
WRITING A FILE
Once we open a file, we can do a number of file operations. Let us see how we can perform the writing operation
on it. The first thing we should remember while writing to a file is that we need to open the file in write mode to
enable us to do the write operation on it.
The write() method can be used to write to any opened file.
Syntax : file_obj.write(string)
Code : Creating a file
f1=open("vaibhav.txt","x")
Code : Opening a file
file1=open("vaibhav.txt")
print(file1)
Output :
<_io.TextIOWrapper name='vaibhav.txt' mode='r' encoding='cp1252'>
Code : Writing a file
f1=open("vaibhav.txt","w")
f1.write("Hello !!")
f1.write("Are you there ?? ")
f1.close()
Output : ( In .txt file ) ( seen by opening the file )
Hello !!Are you there ??
Code :
f1=open("vaibhav.txt","w")
f1.write("Hello !!\n")
f1.write("Are you there ?? ")
f1.close()
Output : ( In .txt file ) ( seen by opening the file )
Hello !!
Are you there ??
The write operation can also be executed by means of writelines() function.
Syntax : file_obj.writelines (sequence)
This method will write a sequence of strings to the file.
Code :
f1=open("vaibhav.txt","w")
f1.writelines(["First line \n","Second line\n","Third line\n","Fourth line \n"])
f1.close()
Output : ( In .txt file ) ( seen by opening the file )
First line
Second line
Third line
Fourth line
Code :
f1=open("vaibhav.txt","w")
lines=["First line \n","Second line\n","Third line\n","Fourth line \n"]
f1.writelines(lines)
f1.close()
Output : ( In .txt file ) ( seen by opening the file )
First line
Second line
Third line
Fourth line
DELETING A FILE
Using the os module
Syntax : import os
os.remove(filename)
Code :
import os
os.remove("vaibhav.txt")
THE FILE POINTER
Once we open a file and start reading from it, the pointer for reading moves according to the type of reading
operation that we do. That is, sometimes it moves from line to line or sometimes it moves from byte to byte.
Let us see here how we can manipulate the movement of the pointer. We will also look into how we can check the
position of the pointer and to change the position in this section.
1. tell()
The tell() method tells the current position of the pointer. This is where the pointer will start to read when we do the
reading operation.
Syntax: filename.tell()
File : vaibhav.txt
Hello !!
Are you there ??
Code :
f1=open("vaibhav.txt","r")
print(f1.tell())
print(f1.read(5))
print(f1.tell())
f1.close()
Output :
0
Hello
5
2. seek()
The seek() function is really a useful function that helps to change the pointer position.
Syntax : filename.seek (size)
Here the size refers to the position where we want to keep the pointer.
NOTE: The value zero when passed to the seek() function will place the pointer at the zeroth position in
the file, that is, in the very beginning. Likewise, when 1 is passed it will place the pointer after the first
element in the file.
File : ( vaibhav.txt )
Hello !!
Are you there ??
Code :
f1=open("vaibhav.txt","r")
print(f1.tell())
print(f1.readline())
print(f1.tell())
f1.seek(2)
print(f1.readline(5))
f1.close()
Output :
0
Hello !!
10
llo !