Humanities/Arts Exam  >  Humanities/Arts Notes  >  NCERT Textbook: File Handling in Python

NCERT Textbook: File Handling in Python - Humanities/Arts PDF Download

Download, print and study this document offline
Please wait while the PDF view is loading
 Page 1


In this Chapter
 » Introduction to Files
 » Types of Files
 » Opening and Closing a 
Text File
 » Writing to a Text File
 » Reading from a Text File
 » Setting Offsets in a File
 » Creating and Traversing a 
Text File
 » The Pickle Module
Chapter
2.1 Introduct Ion to FIles We have so far created programs in Python that 
accept the input, manipulate it and display the 
output. But that output is available only during 
execution of the program and input is to be 
entered through the keyboard. This is because the 
variables used in a program have a lifetime that 
lasts till the time the program is under execution. 
What if we want to store the data that were input 
as well as the generated output permanently so 
that we can reuse it later? Usually, organisations 
would want to permanently store information 
about employees, inventory, sales, etc. to avoid 
repetitive tasks of entering the same data. Hence, 
data are stored permanently on secondary storage 
devices for reusability. We store Python programs 
written in script mode with a .py extension. Each 
program is stored on the secondary device as a 
??le. Likewise, the data entered, and the output 
can be stored permanently into a ??le.
2 
File Handling in 
Python
There are many ways of trying to understand 
programs. People often rely too much on one way, which 
is called "debugging" and consists of running a partly-
understood program to see if it does what you expected. 
Another way, which ML advocates, is to install some means of 
understanding in the very programs themselves.
— Robin Milner
Chapter 2.indd   19 18-Jun-21   2:29:01 PM
Reprint 2025-26
Page 2


In this Chapter
 » Introduction to Files
 » Types of Files
 » Opening and Closing a 
Text File
 » Writing to a Text File
 » Reading from a Text File
 » Setting Offsets in a File
 » Creating and Traversing a 
Text File
 » The Pickle Module
Chapter
2.1 Introduct Ion to FIles We have so far created programs in Python that 
accept the input, manipulate it and display the 
output. But that output is available only during 
execution of the program and input is to be 
entered through the keyboard. This is because the 
variables used in a program have a lifetime that 
lasts till the time the program is under execution. 
What if we want to store the data that were input 
as well as the generated output permanently so 
that we can reuse it later? Usually, organisations 
would want to permanently store information 
about employees, inventory, sales, etc. to avoid 
repetitive tasks of entering the same data. Hence, 
data are stored permanently on secondary storage 
devices for reusability. We store Python programs 
written in script mode with a .py extension. Each 
program is stored on the secondary device as a 
??le. Likewise, the data entered, and the output 
can be stored permanently into a ??le.
2 
File Handling in 
Python
There are many ways of trying to understand 
programs. People often rely too much on one way, which 
is called "debugging" and consists of running a partly-
understood program to see if it does what you expected. 
Another way, which ML advocates, is to install some means of 
understanding in the very programs themselves.
— Robin Milner
Chapter 2.indd   19 18-Jun-21   2:29:01 PM
Reprint 2025-26
Computer SCien Ce - Cla SS Xii File Handling in p yt Hon 20
So, what is a ??le? A ??le is a named location on a 
secondary storage media where data are permanently 
stored for later access.
2.2. t ypes o F FIles Computers store every ??le as a collection of 0s and 1s 
i.e., in binary form. Therefore, every ??le is basically just 
a series of bytes stored one after the other. There are 
mainly two types of data ??les — text ??le and binary 
??le. A text ??le consists of human readable characters, 
which can be opened by any text editor. On the other 
hand, binary ??les are made up of non-human readable 
characters and symbols, which require speci??c programs 
to access its contents.
2.2.1 Text ??le
A text ??le can be understood as a sequence of characters 
consisting of alphabets, numbers and other special 
symbols. Files with extensions like .txt, .py, .csv, etc. 
are some examples of text ??les. When we open a text ??le 
using a text editor (e.g., Notepad), we see several lines 
of text. However, the ??le contents are not stored in such 
a way internally. Rather, they are stored in sequence 
of bytes consisting of 0s and 1s. In ASCII, UNICODE or 
any other encoding scheme, the value of each character 
of the text ??le is stored as bytes. So, while opening a 
text ??le, the text editor translates each ASCII value 
and shows us the equivalent character that is readable 
by the human being. For example, the ASCII value 65 
(binary equivalent 1000001) will be displayed by a text 
editor as the letter ‘A’ since the number 65 in ASCII 
character set represents ‘A’.
Each line of a text ??le is terminated by a special 
character, called the End of Line (EOL). For example, 
the default EOL character in Python is the newline 
(\n). However, other characters can be used to indicate 
EOL. When a text editor or a program interpreter 
encounters the ASCII equivalent of the EOL character, 
it displays the remaining ??le contents starting from a 
new line. Contents in a text ??le are usually separated 
by whitespace, but comma (,) and tab (\t) are also 
commonly used to separate values in a text ??le.
Activity 2.1
Create a text ??le using 
notepad and write 
your name and save it. 
Now, create a .docx ??le 
using Microsoft Word 
and write your name 
and save it as well. 
Check and compare 
the ??le size of both the 
??les. You will ??nd that 
the size of .txt ??le is 
in bytes whereas 
that of .docx is in 
KBs.
Text ??les contain 
only the ASCII 
equivalent of the 
contents of the 
??le whereas a 
.docx ??le contains 
many additional 
information like 
the author's name, 
page settings, font 
type and size, date 
of creation and 
modi??cation, etc.
Chapter 2.indd   20 18-Jun-21   2:29:02 PM
Reprint 2025-26
Page 3


In this Chapter
 » Introduction to Files
 » Types of Files
 » Opening and Closing a 
Text File
 » Writing to a Text File
 » Reading from a Text File
 » Setting Offsets in a File
 » Creating and Traversing a 
Text File
 » The Pickle Module
Chapter
2.1 Introduct Ion to FIles We have so far created programs in Python that 
accept the input, manipulate it and display the 
output. But that output is available only during 
execution of the program and input is to be 
entered through the keyboard. This is because the 
variables used in a program have a lifetime that 
lasts till the time the program is under execution. 
What if we want to store the data that were input 
as well as the generated output permanently so 
that we can reuse it later? Usually, organisations 
would want to permanently store information 
about employees, inventory, sales, etc. to avoid 
repetitive tasks of entering the same data. Hence, 
data are stored permanently on secondary storage 
devices for reusability. We store Python programs 
written in script mode with a .py extension. Each 
program is stored on the secondary device as a 
??le. Likewise, the data entered, and the output 
can be stored permanently into a ??le.
2 
File Handling in 
Python
There are many ways of trying to understand 
programs. People often rely too much on one way, which 
is called "debugging" and consists of running a partly-
understood program to see if it does what you expected. 
Another way, which ML advocates, is to install some means of 
understanding in the very programs themselves.
— Robin Milner
Chapter 2.indd   19 18-Jun-21   2:29:01 PM
Reprint 2025-26
Computer SCien Ce - Cla SS Xii File Handling in p yt Hon 20
So, what is a ??le? A ??le is a named location on a 
secondary storage media where data are permanently 
stored for later access.
2.2. t ypes o F FIles Computers store every ??le as a collection of 0s and 1s 
i.e., in binary form. Therefore, every ??le is basically just 
a series of bytes stored one after the other. There are 
mainly two types of data ??les — text ??le and binary 
??le. A text ??le consists of human readable characters, 
which can be opened by any text editor. On the other 
hand, binary ??les are made up of non-human readable 
characters and symbols, which require speci??c programs 
to access its contents.
2.2.1 Text ??le
A text ??le can be understood as a sequence of characters 
consisting of alphabets, numbers and other special 
symbols. Files with extensions like .txt, .py, .csv, etc. 
are some examples of text ??les. When we open a text ??le 
using a text editor (e.g., Notepad), we see several lines 
of text. However, the ??le contents are not stored in such 
a way internally. Rather, they are stored in sequence 
of bytes consisting of 0s and 1s. In ASCII, UNICODE or 
any other encoding scheme, the value of each character 
of the text ??le is stored as bytes. So, while opening a 
text ??le, the text editor translates each ASCII value 
and shows us the equivalent character that is readable 
by the human being. For example, the ASCII value 65 
(binary equivalent 1000001) will be displayed by a text 
editor as the letter ‘A’ since the number 65 in ASCII 
character set represents ‘A’.
Each line of a text ??le is terminated by a special 
character, called the End of Line (EOL). For example, 
the default EOL character in Python is the newline 
(\n). However, other characters can be used to indicate 
EOL. When a text editor or a program interpreter 
encounters the ASCII equivalent of the EOL character, 
it displays the remaining ??le contents starting from a 
new line. Contents in a text ??le are usually separated 
by whitespace, but comma (,) and tab (\t) are also 
commonly used to separate values in a text ??le.
Activity 2.1
Create a text ??le using 
notepad and write 
your name and save it. 
Now, create a .docx ??le 
using Microsoft Word 
and write your name 
and save it as well. 
Check and compare 
the ??le size of both the 
??les. You will ??nd that 
the size of .txt ??le is 
in bytes whereas 
that of .docx is in 
KBs.
Text ??les contain 
only the ASCII 
equivalent of the 
contents of the 
??le whereas a 
.docx ??le contains 
many additional 
information like 
the author's name, 
page settings, font 
type and size, date 
of creation and 
modi??cation, etc.
Chapter 2.indd   20 18-Jun-21   2:29:02 PM
Reprint 2025-26
Computer SCien Ce - Cla SS Xii File Handling in p yt Hon 21
The ??le_object 
establishes a 
link between the 
program and the 
data ??le stored 
in the permanent 
storage.
2.2.2 Binary Files
Binary ??les are also stored in terms of bytes (0s and 1s), 
but unlike text ??les, these bytes do not represent the 
ASCII values of characters. Rather, they represent the 
actual content such as image, audio, video, compressed 
versions of other ??les, executable ??les, etc. These ??les 
are not human readable. Thus, trying to open a binary 
??le using a text editor will show some garbage values. 
We need speci??c software to read or write the contents 
of a binary ??le. 
Binary ??les are stored in a computer in a sequence 
of bytes. Even a single bit change can corrupt the ??le 
and make it unreadable to the supporting application. 
Also, it is dif??cult to remove any error which may occur 
in the binary ??le as the stored contents are not human 
readable. We can read and write both text and binary 
??les through Python programs.
2.3 o pen Ing and c los Ing a t ext FIle In real world applications, computer programs deal 
with data coming from different sources like databases, 
CSV ??les, HTML, XML, JSON, etc. We broadly access 
??les either to write or read data from it. But operations 
on ??les include creating and opening a ??le, writing data 
in a ??le, traversing a ??le, reading data from a ??le and 
so on. Python has the io module that contains different 
functions for handling ??les. 
2.3.1 Opening a ??le
To open a ??le in Python, we use the open() function. The 
syntax of open() is as follows:
 ??le_object= open(??le_name, access_mode)
This function returns a ??le object called ??le handle 
which is stored in the variable ??le_object . We can 
use this variable to transfer data to and from the ??le 
(read and write) by calling the functions de??ned in the 
Python’s io module. If the ??le does not exist, the above 
statement creates a new empty ??le and assigns it the 
name we specify in the statement.
The ??le_object has certain attributes that tells us 
basic information about the ??le, such as:
• <??le.closed> returns true if the ??le is closed and 
false otherwise.
Chapter 2.indd   21 18-Jun-21   2:29:02 PM
Reprint 2025-26
Page 4


In this Chapter
 » Introduction to Files
 » Types of Files
 » Opening and Closing a 
Text File
 » Writing to a Text File
 » Reading from a Text File
 » Setting Offsets in a File
 » Creating and Traversing a 
Text File
 » The Pickle Module
Chapter
2.1 Introduct Ion to FIles We have so far created programs in Python that 
accept the input, manipulate it and display the 
output. But that output is available only during 
execution of the program and input is to be 
entered through the keyboard. This is because the 
variables used in a program have a lifetime that 
lasts till the time the program is under execution. 
What if we want to store the data that were input 
as well as the generated output permanently so 
that we can reuse it later? Usually, organisations 
would want to permanently store information 
about employees, inventory, sales, etc. to avoid 
repetitive tasks of entering the same data. Hence, 
data are stored permanently on secondary storage 
devices for reusability. We store Python programs 
written in script mode with a .py extension. Each 
program is stored on the secondary device as a 
??le. Likewise, the data entered, and the output 
can be stored permanently into a ??le.
2 
File Handling in 
Python
There are many ways of trying to understand 
programs. People often rely too much on one way, which 
is called "debugging" and consists of running a partly-
understood program to see if it does what you expected. 
Another way, which ML advocates, is to install some means of 
understanding in the very programs themselves.
— Robin Milner
Chapter 2.indd   19 18-Jun-21   2:29:01 PM
Reprint 2025-26
Computer SCien Ce - Cla SS Xii File Handling in p yt Hon 20
So, what is a ??le? A ??le is a named location on a 
secondary storage media where data are permanently 
stored for later access.
2.2. t ypes o F FIles Computers store every ??le as a collection of 0s and 1s 
i.e., in binary form. Therefore, every ??le is basically just 
a series of bytes stored one after the other. There are 
mainly two types of data ??les — text ??le and binary 
??le. A text ??le consists of human readable characters, 
which can be opened by any text editor. On the other 
hand, binary ??les are made up of non-human readable 
characters and symbols, which require speci??c programs 
to access its contents.
2.2.1 Text ??le
A text ??le can be understood as a sequence of characters 
consisting of alphabets, numbers and other special 
symbols. Files with extensions like .txt, .py, .csv, etc. 
are some examples of text ??les. When we open a text ??le 
using a text editor (e.g., Notepad), we see several lines 
of text. However, the ??le contents are not stored in such 
a way internally. Rather, they are stored in sequence 
of bytes consisting of 0s and 1s. In ASCII, UNICODE or 
any other encoding scheme, the value of each character 
of the text ??le is stored as bytes. So, while opening a 
text ??le, the text editor translates each ASCII value 
and shows us the equivalent character that is readable 
by the human being. For example, the ASCII value 65 
(binary equivalent 1000001) will be displayed by a text 
editor as the letter ‘A’ since the number 65 in ASCII 
character set represents ‘A’.
Each line of a text ??le is terminated by a special 
character, called the End of Line (EOL). For example, 
the default EOL character in Python is the newline 
(\n). However, other characters can be used to indicate 
EOL. When a text editor or a program interpreter 
encounters the ASCII equivalent of the EOL character, 
it displays the remaining ??le contents starting from a 
new line. Contents in a text ??le are usually separated 
by whitespace, but comma (,) and tab (\t) are also 
commonly used to separate values in a text ??le.
Activity 2.1
Create a text ??le using 
notepad and write 
your name and save it. 
Now, create a .docx ??le 
using Microsoft Word 
and write your name 
and save it as well. 
Check and compare 
the ??le size of both the 
??les. You will ??nd that 
the size of .txt ??le is 
in bytes whereas 
that of .docx is in 
KBs.
Text ??les contain 
only the ASCII 
equivalent of the 
contents of the 
??le whereas a 
.docx ??le contains 
many additional 
information like 
the author's name, 
page settings, font 
type and size, date 
of creation and 
modi??cation, etc.
Chapter 2.indd   20 18-Jun-21   2:29:02 PM
Reprint 2025-26
Computer SCien Ce - Cla SS Xii File Handling in p yt Hon 21
The ??le_object 
establishes a 
link between the 
program and the 
data ??le stored 
in the permanent 
storage.
2.2.2 Binary Files
Binary ??les are also stored in terms of bytes (0s and 1s), 
but unlike text ??les, these bytes do not represent the 
ASCII values of characters. Rather, they represent the 
actual content such as image, audio, video, compressed 
versions of other ??les, executable ??les, etc. These ??les 
are not human readable. Thus, trying to open a binary 
??le using a text editor will show some garbage values. 
We need speci??c software to read or write the contents 
of a binary ??le. 
Binary ??les are stored in a computer in a sequence 
of bytes. Even a single bit change can corrupt the ??le 
and make it unreadable to the supporting application. 
Also, it is dif??cult to remove any error which may occur 
in the binary ??le as the stored contents are not human 
readable. We can read and write both text and binary 
??les through Python programs.
2.3 o pen Ing and c los Ing a t ext FIle In real world applications, computer programs deal 
with data coming from different sources like databases, 
CSV ??les, HTML, XML, JSON, etc. We broadly access 
??les either to write or read data from it. But operations 
on ??les include creating and opening a ??le, writing data 
in a ??le, traversing a ??le, reading data from a ??le and 
so on. Python has the io module that contains different 
functions for handling ??les. 
2.3.1 Opening a ??le
To open a ??le in Python, we use the open() function. The 
syntax of open() is as follows:
 ??le_object= open(??le_name, access_mode)
This function returns a ??le object called ??le handle 
which is stored in the variable ??le_object . We can 
use this variable to transfer data to and from the ??le 
(read and write) by calling the functions de??ned in the 
Python’s io module. If the ??le does not exist, the above 
statement creates a new empty ??le and assigns it the 
name we specify in the statement.
The ??le_object has certain attributes that tells us 
basic information about the ??le, such as:
• <??le.closed> returns true if the ??le is closed and 
false otherwise.
Chapter 2.indd   21 18-Jun-21   2:29:02 PM
Reprint 2025-26
Computer SCien Ce - Cla SS Xii File Handling in p yt Hon 22
• <??le.mode> returns the access mode in which the 
??le was opened.
• <??le.name> returns the name of the ??le.
The ??le_name should be the name of the ??le that 
has to be opened. If the ??le is not in the current working 
directory, then we need to specify the complete path of 
the ??le along with its name.
The access_mode is an optional argument that 
represents the mode in which the ??le has to be accessed 
by the program. It is also referred to as processing mode. 
Here mode means the operation for which the ??le has 
to be opened like <r> for reading, <w> for writing, <+> 
for both reading and writing, <a> for appending at the 
end of an existing ??le. The default is the read mode. In 
addition, we can specify whether the ??le will be handled 
as binary (<b>) or text mode. By default, ??les are opened 
in text mode that means strings can be read or written. 
Files containing non-textual data are opened in binary 
mode that means read/write are performed in terms of 
bytes. Table 2.1 lists various ??le access modes that can 
be used with the open() method. The ??le offset position 
in the table refers to the position of the ??le object when 
the ??le is opened in a particular mode.
Table 2.1 File Open Modes
File Mode Description File Offset position
<r> Opens the ??le in read-only mode. Beginning of the ??le
<rb> Opens the ??le in binary and read-only mode. Beginning of the ??le
<r+> or <+r> Opens the ??le in both read and write mode. Beginning of the ??le
<w> Opens the ??le in write mode. If the ??le already exists, all the 
contents will be overwritten. If the ??le doesn’t exist, then a 
new ??le will be created.
Beginning of the ??le
<wb+> or 
<+wb>
Opens the ??le in read,write and binary mode. If the ??le 
already exists, the contents will be overwritten. If the ??le 
doesn’t exist, then a new ??le will be created.
Beginning of the ??le
<a> Opens the ??le in append mode. If the ??le doesn’t exist, then 
a new ??le will be created.
End of the ??le
<a+> or <+a> Opens the ??le in append and read mode. If the ??le doesn’t 
exist, then it will create a new ??le.
End of the ??le
Activity 2.2
Some of the other 
??le access modes are 
<rb+>, <wb>, <w+>, 
<ab>, <ab+>. Find out 
for what purpose each 
of these are used. 
Also, ??nd the ??le 
offset positions in 
each case.
Consider the following example.
myObject=open(“my??le.txt”, “a+”)
Chapter 2.indd   22 18-Jun-21   2:29:02 PM
Reprint 2025-26
Page 5


In this Chapter
 » Introduction to Files
 » Types of Files
 » Opening and Closing a 
Text File
 » Writing to a Text File
 » Reading from a Text File
 » Setting Offsets in a File
 » Creating and Traversing a 
Text File
 » The Pickle Module
Chapter
2.1 Introduct Ion to FIles We have so far created programs in Python that 
accept the input, manipulate it and display the 
output. But that output is available only during 
execution of the program and input is to be 
entered through the keyboard. This is because the 
variables used in a program have a lifetime that 
lasts till the time the program is under execution. 
What if we want to store the data that were input 
as well as the generated output permanently so 
that we can reuse it later? Usually, organisations 
would want to permanently store information 
about employees, inventory, sales, etc. to avoid 
repetitive tasks of entering the same data. Hence, 
data are stored permanently on secondary storage 
devices for reusability. We store Python programs 
written in script mode with a .py extension. Each 
program is stored on the secondary device as a 
??le. Likewise, the data entered, and the output 
can be stored permanently into a ??le.
2 
File Handling in 
Python
There are many ways of trying to understand 
programs. People often rely too much on one way, which 
is called "debugging" and consists of running a partly-
understood program to see if it does what you expected. 
Another way, which ML advocates, is to install some means of 
understanding in the very programs themselves.
— Robin Milner
Chapter 2.indd   19 18-Jun-21   2:29:01 PM
Reprint 2025-26
Computer SCien Ce - Cla SS Xii File Handling in p yt Hon 20
So, what is a ??le? A ??le is a named location on a 
secondary storage media where data are permanently 
stored for later access.
2.2. t ypes o F FIles Computers store every ??le as a collection of 0s and 1s 
i.e., in binary form. Therefore, every ??le is basically just 
a series of bytes stored one after the other. There are 
mainly two types of data ??les — text ??le and binary 
??le. A text ??le consists of human readable characters, 
which can be opened by any text editor. On the other 
hand, binary ??les are made up of non-human readable 
characters and symbols, which require speci??c programs 
to access its contents.
2.2.1 Text ??le
A text ??le can be understood as a sequence of characters 
consisting of alphabets, numbers and other special 
symbols. Files with extensions like .txt, .py, .csv, etc. 
are some examples of text ??les. When we open a text ??le 
using a text editor (e.g., Notepad), we see several lines 
of text. However, the ??le contents are not stored in such 
a way internally. Rather, they are stored in sequence 
of bytes consisting of 0s and 1s. In ASCII, UNICODE or 
any other encoding scheme, the value of each character 
of the text ??le is stored as bytes. So, while opening a 
text ??le, the text editor translates each ASCII value 
and shows us the equivalent character that is readable 
by the human being. For example, the ASCII value 65 
(binary equivalent 1000001) will be displayed by a text 
editor as the letter ‘A’ since the number 65 in ASCII 
character set represents ‘A’.
Each line of a text ??le is terminated by a special 
character, called the End of Line (EOL). For example, 
the default EOL character in Python is the newline 
(\n). However, other characters can be used to indicate 
EOL. When a text editor or a program interpreter 
encounters the ASCII equivalent of the EOL character, 
it displays the remaining ??le contents starting from a 
new line. Contents in a text ??le are usually separated 
by whitespace, but comma (,) and tab (\t) are also 
commonly used to separate values in a text ??le.
Activity 2.1
Create a text ??le using 
notepad and write 
your name and save it. 
Now, create a .docx ??le 
using Microsoft Word 
and write your name 
and save it as well. 
Check and compare 
the ??le size of both the 
??les. You will ??nd that 
the size of .txt ??le is 
in bytes whereas 
that of .docx is in 
KBs.
Text ??les contain 
only the ASCII 
equivalent of the 
contents of the 
??le whereas a 
.docx ??le contains 
many additional 
information like 
the author's name, 
page settings, font 
type and size, date 
of creation and 
modi??cation, etc.
Chapter 2.indd   20 18-Jun-21   2:29:02 PM
Reprint 2025-26
Computer SCien Ce - Cla SS Xii File Handling in p yt Hon 21
The ??le_object 
establishes a 
link between the 
program and the 
data ??le stored 
in the permanent 
storage.
2.2.2 Binary Files
Binary ??les are also stored in terms of bytes (0s and 1s), 
but unlike text ??les, these bytes do not represent the 
ASCII values of characters. Rather, they represent the 
actual content such as image, audio, video, compressed 
versions of other ??les, executable ??les, etc. These ??les 
are not human readable. Thus, trying to open a binary 
??le using a text editor will show some garbage values. 
We need speci??c software to read or write the contents 
of a binary ??le. 
Binary ??les are stored in a computer in a sequence 
of bytes. Even a single bit change can corrupt the ??le 
and make it unreadable to the supporting application. 
Also, it is dif??cult to remove any error which may occur 
in the binary ??le as the stored contents are not human 
readable. We can read and write both text and binary 
??les through Python programs.
2.3 o pen Ing and c los Ing a t ext FIle In real world applications, computer programs deal 
with data coming from different sources like databases, 
CSV ??les, HTML, XML, JSON, etc. We broadly access 
??les either to write or read data from it. But operations 
on ??les include creating and opening a ??le, writing data 
in a ??le, traversing a ??le, reading data from a ??le and 
so on. Python has the io module that contains different 
functions for handling ??les. 
2.3.1 Opening a ??le
To open a ??le in Python, we use the open() function. The 
syntax of open() is as follows:
 ??le_object= open(??le_name, access_mode)
This function returns a ??le object called ??le handle 
which is stored in the variable ??le_object . We can 
use this variable to transfer data to and from the ??le 
(read and write) by calling the functions de??ned in the 
Python’s io module. If the ??le does not exist, the above 
statement creates a new empty ??le and assigns it the 
name we specify in the statement.
The ??le_object has certain attributes that tells us 
basic information about the ??le, such as:
• <??le.closed> returns true if the ??le is closed and 
false otherwise.
Chapter 2.indd   21 18-Jun-21   2:29:02 PM
Reprint 2025-26
Computer SCien Ce - Cla SS Xii File Handling in p yt Hon 22
• <??le.mode> returns the access mode in which the 
??le was opened.
• <??le.name> returns the name of the ??le.
The ??le_name should be the name of the ??le that 
has to be opened. If the ??le is not in the current working 
directory, then we need to specify the complete path of 
the ??le along with its name.
The access_mode is an optional argument that 
represents the mode in which the ??le has to be accessed 
by the program. It is also referred to as processing mode. 
Here mode means the operation for which the ??le has 
to be opened like <r> for reading, <w> for writing, <+> 
for both reading and writing, <a> for appending at the 
end of an existing ??le. The default is the read mode. In 
addition, we can specify whether the ??le will be handled 
as binary (<b>) or text mode. By default, ??les are opened 
in text mode that means strings can be read or written. 
Files containing non-textual data are opened in binary 
mode that means read/write are performed in terms of 
bytes. Table 2.1 lists various ??le access modes that can 
be used with the open() method. The ??le offset position 
in the table refers to the position of the ??le object when 
the ??le is opened in a particular mode.
Table 2.1 File Open Modes
File Mode Description File Offset position
<r> Opens the ??le in read-only mode. Beginning of the ??le
<rb> Opens the ??le in binary and read-only mode. Beginning of the ??le
<r+> or <+r> Opens the ??le in both read and write mode. Beginning of the ??le
<w> Opens the ??le in write mode. If the ??le already exists, all the 
contents will be overwritten. If the ??le doesn’t exist, then a 
new ??le will be created.
Beginning of the ??le
<wb+> or 
<+wb>
Opens the ??le in read,write and binary mode. If the ??le 
already exists, the contents will be overwritten. If the ??le 
doesn’t exist, then a new ??le will be created.
Beginning of the ??le
<a> Opens the ??le in append mode. If the ??le doesn’t exist, then 
a new ??le will be created.
End of the ??le
<a+> or <+a> Opens the ??le in append and read mode. If the ??le doesn’t 
exist, then it will create a new ??le.
End of the ??le
Activity 2.2
Some of the other 
??le access modes are 
<rb+>, <wb>, <w+>, 
<ab>, <ab+>. Find out 
for what purpose each 
of these are used. 
Also, ??nd the ??le 
offset positions in 
each case.
Consider the following example.
myObject=open(“my??le.txt”, “a+”)
Chapter 2.indd   22 18-Jun-21   2:29:02 PM
Reprint 2025-26
Computer SCien Ce - Cla SS Xii File Handling in p yt Hon 23
In the above statement, the ??le my??le.txt is opened 
in append and read modes. The ??le object will be at the 
end of the ??le. That means we can write data at the end 
of the ??le and at the same time we can also read data 
from the ??le using the ??le object named myObject.
2.3.2 Closing a ??le
Once we are done with the read/write operations on a 
??le, it is a good practice to close the ??le. Python provides 
a close() method to do so. While closing a ??le, the 
system frees the memory allocated to it. The syntax of 
close() is:
??le_object.close()
Here, ??le_object is the object that was returned while 
opening the ??le. 
Python makes sure that any unwritten or unsaved 
data is ??ushed off (written) to the ??le before it is closed. 
Hence, it is always advised to close the ??le once our 
work is done. Also, if the ??le object is re-assigned to 
some other ??le, the previous ??le is automatically closed.
2.3.3 Opening a ??le using with clause
In Python, we can also open a ??le using with clause. 
The syntax of with clause is:
with open (??le_name, access_mode) as ??le_
object:
The advantage of using with clause is that any ??le 
that is opened using this clause is closed automatically, 
once the control comes outside the with clause. In 
case the user forgets to close the ??le explicitly or if an 
exception occurs, the ??le is closed automatically. Also, 
it provides a simpler syntax.
with open(“my??le.txt”,”r+”) as myObject:
 content = myObject.read()
Here, we don’t have to close the ??le explicitly  
using close() statement. Python will automatically close 
the ??le.
2.4 Wr It Ing to a t ext FIle For writing to a ??le, we ??rst need to open it in write or 
append mode. If we open an existing ??le in write mode, 
the previous data will be erased, and the ??le object will 
be positioned at the beginning of the ??le. On the other 
n otes Chapter 2.indd   23 18-Jun-21   2:29:02 PM
Reprint 2025-26
Read More

FAQs on NCERT Textbook: File Handling in Python - Humanities/Arts

1. What is file handling in Python?
Ans.File handling in Python refers to the process of using built-in functions and methods to create, read, update, and delete files on a computer. It allows programmers to manage data stored in files, making it easier to work with large amounts of information and perform various operations on that data.
2. How can I read a file in Python?
Ans.To read a file in Python, you can use the built-in `open()` function to open the file in read mode, and then use the `read()`, `readline()`, or `readlines()` methods to retrieve its content. For example: python file = open('filename.txt', 'r') content = file.read() file.close() This code opens a file called 'filename.txt', reads its entire content, and then closes the file.
3. What are the different modes for opening a file in Python?
Ans.Python supports several modes for opening files: - `'r'` for reading (default mode), - `'w'` for writing (overwrites existing files), - `'a'` for appending (adds data to the end of the file), - `'b'` for binary mode (reads/writes binary files), - `'x'` for exclusive creation (fails if the file already exists). You can also combine these modes, such as `'rb'` for reading binary files.
4. How do I write to a file in Python?
Ans.To write to a file in Python, you can open the file in write mode (`'w'`) or append mode (`'a'`). Then, use the `write()` method to add text to the file. For example: python file = open('filename.txt', 'w') file.write('Hello, World!') file.close() This code opens 'filename.txt' in write mode, writes "Hello, World!" to it, and then closes the file.
5. What is the significance of closing a file in Python?
Ans.Closing a file in Python is crucial because it ensures that all data is properly written and resources are released. If a file is not closed, it may lead to data corruption or loss, and the program may run out of file handles. Always use `file.close()` or a context manager (using `with open(...)`) to ensure files are closed properly after their use.
Download as PDF

Top Courses for Humanities/Arts

Related Searches

Previous Year Questions with Solutions

,

Important questions

,

NCERT Textbook: File Handling in Python - Humanities/Arts

,

pdf

,

Exam

,

shortcuts and tricks

,

Semester Notes

,

practice quizzes

,

study material

,

Viva Questions

,

Free

,

past year papers

,

mock tests for examination

,

Sample Paper

,

MCQs

,

NCERT Textbook: File Handling in Python - Humanities/Arts

,

NCERT Textbook: File Handling in Python - Humanities/Arts

,

video lectures

,

Objective type Questions

,

Extra Questions

,

ppt

,

Summary

;