Computer Science
Chapter-02
File Handling in Python
Introduction:
The data are stored permanently on secondary storage devices for
reusability.
Each program is stored on the secondary device as a file. Likewise,
the data entered, and the output can be stored permanently into a
file for future access.
File:
Definition: A file is a named location on a secondary storage media
where data are permanently stored for later access.
Computers store every file as a collection of 0s and 1s i.e., in binary
form.
Therefore, every file is basically just a series of bytes stored one
after the other.
There are mainly two types of data files
1. Text Files
2. Binary Files
1. Text Files
A text file is a file that contains a sequence of characters
including alphabets, numbers and other special symbols.
Each line in a text file is usually terminated with a special
character called EOL [End of Line] character.
By default ’\n’ [newline] is used as EOL in python.
Contents in a text file are usually separated by whitespace,
comma (,) and tab (\t).
Files with extensions like .txt, .py, .csv, etc. are some examples
of text files.
Internally the text file contents are stored in sequence of bytes
consists of 0s and 1s [in ASCII or UNICODE and other format].
While opening a text file, a text editor translates the binary data
into readable characters. [For example: ASCII value
65(1000001) will display the letter ‘A’ by a text editor].
2. Binary Files:
In binary files, data is stored in byte format.
If we try to open a binary file using a text editor, it will show
some garbage values.
CHAITHRA N, Lecturer in CS dept. BGS College, Mysore 1
Computer Science
Even a single bit change can corrupt the file and make it
unreadable to the supporting application.
It is difficult to debug errors in a binary file because the data is
not in human readable form.
We can read and write both text and binary files through
Python programs.
Opening a file:
To open a file in Python, we use the open() function.
The syntax of open() is as follows:
file_object = open(file_name, access_mode)
where,
The file_name should be the name of the file that has
to be opened.
The access_mode is an optional argument that
represents the mode in which the file has to be
accessed by the program.
Open() function returns a file object called file handle which is
stored in the variable file_object.
The file_object has certain attributes that tells us basic
information about the file, such as:
a) <[Link]> returns true if the file is closed and false
otherwise.
b) <[Link]> returns the access mode in which the f ile was
opened. Activity
c) <[Link]> returns the name of the file.
Note: The file_object establishes a link between the program and
the data file stored in the permanent storage.
access_mode:
It is also referred as processing mode. Here mode means the
operation for which the file 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 file etc.
By default the files are opened in read mode.
By using access mode we can also mention whether the file will
be handled as binary(<b>) or text mode.
By default, files are opened in text mode that means strings can
be read or written.
Files are opened in binary mode that means read/write are
performed in terms of bytes.
The following table represents the various file access modes that
can be used with the open() method.
CHAITHRA N, Lecturer in CS dept. BGS College, Mysore 2
Computer Science
In the table, the file offset position refers to the position of the file
object when the file is opened in a particular mode.
Example to open():
myObject=open(“[Link]”, “a+”)
In the above example, the file [Link] is opened in append
and read modes.
The file object will be at the end of the file. That means we can
write data at the end of the file and at the same time we can also
read data from the file using the file object named myObject.
Closing a file:
After performing read/write operation on a file, we have to close
it.
Python provides a close() method to close the file.
While closing a file, the system frees the memory allocated to it.
The syntax of close() is: file_object.close()
When we close the file, python make sure that the
buffered(unsaved) data is flushed-which means it forces that
data to be written to the file on disk.
Buffer- is a temporary storage area in memory(RAM) used to hold
the data temporarily.
flush()- is a method(function) used to clear the buffer by writing
its contents to the file.
If the file object is re-assigned to some other file, the previous file
is automatically closed.
Opening a file using with clause:
In Python, we can also open a file using with clause.
The syntax of with clause is:
CHAITHRA N, Lecturer in CS dept. BGS College, Mysore 3
Computer Science
with open (file_name, access_mode) as file_ object:
Example:
with open(“[Link]”,”r+”) as myObject:
content = [Link]()
The advantage of using with clause is that any file that is opened
using this clause is closed automatically, once the control comes
outside of with clause.
Writing To A Text File:
To write data into the file, first we need to open it in write or
append mode.
If we open an existing file in write mode, the previous data will be
erased, and the file object will be positioned at the beginning of
the file.
If we open a file in append mode, new data will be added at the
end of the previous data as the file object is at the end of the file.
We use two method to write the data into the file.
1) write() - for writing a single string
2) writelines() - for writing a sequence of strings
1) The write() method:
write() method takes a string as an argument and writes it
into the text file.
It returns how many characters are written into the file.
Example-1:
>>> myobject=open("[Link]",'w')
>>> [Link] ("Computer Science\n")
17
>>> [Link]()
Example-2:[To write numeric data]
>>> myobject=open("[Link]",'w')
>>> marks=58
# converts numeric data into
>>> [Link](str(marks))
sting using str function.
2
>>> [Link]()
Write() method writes the data into a buffer, when the close()
method is executed, the contents from this buffer are moved
to the file located on the permanent storage.
2) The writelines() method:
Writelines() method is used to write multiple strings to a file.
CHAITHRA N, Lecturer in CS dept. BGS College, Mysore 4
Computer Science
We need to pass an iterable object like lists, tuple, etc.
The writelines() method does not return the number of
characters written into the file.
Example:
>>> myobject=open("[Link]",'w')
>>>lines=["Hai students\n", "Welcome\n",
"To II PUC\n"]
>>> [Link](lines)
>>> [Link]()
On opening [Link], using notepad, its content will appear
as shown in Figure
Reading From A Text File:
We can write a program to read the contents of a file.
Before reading a file, we must make sure that the file is opened in
“r”, “r+”, “w+” or “a+” mode.
There are three ways to read the contents of a file:
1) The read() method:
This method is used to read a specified number of bytes of
data from a data file.
The syntax of read() method is:
file_object.read(n)
Example:
>>>myobject=open("[Link]",'r')
>>> [Link](5)
‘Hai s’
>>> [Link]()
If no argument or a negative number is specified in read(), the
entire file content is read.
Example:
>>> myobject=open("[Link]",'r')
>>> print([Link]())
Hai students
Welcome
To II PUC
CHAITHRA N, Lecturer in CS dept. BGS College, Mysore 5
Computer Science
>>> [Link]()
2) The readline([n]) method:
This method reads one complete line from first character to
last newline (\n) character.
It can also be used to read a specified number (n) of bytes
from of data from a file but maximum up to the newline
character (\n).
Example:
>>> myobject=open("[Link]",'r')
>>> [Link](10)
‘Hai studen’
>>> [Link]()
If no argument or a negative number is specified, it reads a
complete line and returns string.
Example:
>>>myobject=open("[Link]",'r')
>>> print ([Link]())
‘Hai students\n’
To read the entire file line by line using the readline(), we can
use a loop. This process is known as looping/ iterating over a
file object.
3) The readlines() method:
This method reads all the lines and returns the lines along
with newline as a list of strings.
Example:
>>> myobject=open("[Link]", 'r')
>>> print([Link]())
["Hai students\n", "Welcome\n", "To II PUC\n"]
>>> [Link]()
If we want to display each word of a line separately as an
element of a list, then we can use split() function.
Example for split():
>>> myobject=open("[Link]",'r')
>>> d=[Link]()
>>> for line in d:
words=[Link]()
print(words)
[‘Hai’, ‘students’]
[‘Welcome’]
[‘To’, ‘II’, ‘PUC’]
CHAITHRA N, Lecturer in CS dept. BGS College, Mysore 6
Computer Science
In the above output, each string is returned as elements of a
list.
However, if splitlines() is used instead of split(), then each line
is returned as element of a list.
Example for split():
>>> myobject=open("[Link]",'r')
>>> d=[Link]()
>>> for line in d:
words=[Link]()
print(words)
[‘Hai students’]
[‘Welcome’]
[‘To II PUC’]
Writing and reading to a text file:
Setting Offsets In A File:
seek() and tell() functions are used to access the data of a file
randomly.
1) The tell() method:
tell() function returns an integer which specifies the current
position of the file object in the file.
The syntax of using tell() is:
file_object.tell()
2) The seek() method:
CHAITHRA N, Lecturer in CS dept. BGS College, Mysore 7
Computer Science
This method is used to position the file object at a particular
position in a file.
The syntax of seek() is:
file_object.seek(offset [, reference_point])
Where,
-offset is the number of bytes by which the file object is to be
moved.
-reference_point indicates the starting position of the file
object.
-reference_point can have any of the following values:
0 - beginning of the file
1 - Current position of the file
2 - End of file
-By default, the value of reference_point is 0
For example, the statement [Link](5,0) will position
the file object at 5th byte position from the beginning of the file.
Creating And Traversing A Text File:
We can perform some basic operations on a file.
1. Creating a file and writing data:
To create a text file, we use the open() method and provide the
filename and the mode.
And to write the data into that file we have to use write or
append mode.
Program - To create a text file and write data in it
CHAITHRA N, Lecturer in CS dept. BGS College, Mysore 8
Computer Science
2. Traversing a file and displaying data:
To read the data, the file will be opened in read mode and
reading will begin from the beginning of the file.
In the above example program, the readline() is used in the
while loop to read the data line by line from the text file.
Example Program to perform reading and writing operation in
a text file.
CHAITHRA N, Lecturer in CS dept. BGS College, Mysore 9
Computer Science
The Pickle Module:
Python considers everything as an object.
So, all data types including list, tuple, dictionary, etc. are also
considered as objects.
During execution of a program, we may require to store current
state of variables so that we can retrieve them later to its present
state.
The Pickle module is used to save python object structures along
with data.
The module Pickle is used for serializing and de-serializing any
Python object structure.
Serialization (Pickling) is the Process of converting data or python
objects in memory(RAM) to a stream of bytes called byte stream.
The Serialization process is also called pickling.
Deserialization (Unpickling): The Process of converting a byte
stream into a python object.
CHAITHRA N, Lecturer in CS dept. BGS College, Mysore 10
Computer Science
Generally pickling is a method to store food items for later
consumption.
The pickle module deals with binary files. Here, data are not
written but dumped and similarly, data are not read but loaded.
The pickle module provides two methods - dump() and load() to
work with binary files for pickling and unpickling, respectively.
1) The dump() method:
This method is used to convert (pickling) Python objects for
writing data in a binary file.
The file in which data are to be dumped, needs to be opened in
binary write mode (wb).
Syntax of dump() is as follows:
dump(data_object, file_object)
Where, data_object is the object that has to be dumped to the
file with the file handle named file_object.
Example program for Pickling data in Python
2) The load() method:
This method is used to load (unpickling) data from a binary file.
The file to be loaded is opened in binary read (rb) mode.
Syntax of load() is as follows:
Store_object = load(file_object)
Here, the pickled Python object is loaded from the file having a
file handle named file_object and is stored in a new file handle
called store_object.
Example program for Unpickling data in Python.
CHAITHRA N, Lecturer in CS dept. BGS College, Mysore 11
Computer Science
File handling using pickle module:
As we read and write data in a text file, similarly we will be adding
and displaying data for a binary file.
Example program to perform basic operations on a binary file
using pickle module.
CHAITHRA N, Lecturer in CS dept. BGS College, Mysore 12
Computer Science
Out put:
CHAITHRA N, Lecturer in CS dept. BGS College, Mysore 13
Computer Science
As each employee record is stored as a list in the file, hence while
reading the file, a list is displayed showing record of each
employee.
We have also used try.. except block to handle the end-of-file
exception.
****************************
CHAITHRA N, Lecturer in CS dept. BGS College, Mysore 14