Chapter 2: File Handling in Python
Introduction to Files
A File is a named location on a secondary storage media where data are
permanently stored for later access.
Data are stored permanently on secondary storage devices for reusability.
The data entered, and the output can be stored permanently into a file.
Types of Files
There are mainly two types of data files — text file and binary file.
A text file consists of human readable characters, which can be opened by
any text editor.
Binary files are made up of non-human readable characters and symbols,
which require specific programs to access its contents
Text file:
A text file 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
files.
The value of each character of the text file is stored as bytes.
Each line of a text file is terminated by a special character, called the
End of Line (EOL).
[Link] Page 1
Binary file:
Binary files are also stored in terms of bytes (0s and 1s),
They represent the actual content such as image, audio, video,
compressed versions of other files, executable files, etc.
These files are not human readable. We need specific software to read
or write the contents of a binary file.
it is difficult to remove any error which may occur in the binary file as
the stored contents are not human readable.
Opening and Closing a Text File
We access files either to write or read data from it. But operations on files
include creating and opening a file, writing data in a file, traversing a file,
reading data from a file and so on.
Python has the io module that contains different functions for handling files.
Opening a file:
To work with a file, you first need to open it using open() function.
Syntax:
file_object = open("file_name", "access_mode")
file_name is the name of the file.
Access mode is an optional argument that represents the mode in which the
file has to be accessed by the program. 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.
Example:
file = open("[Link]", "r")
opens a file for reading.
[Link] Page 2
The default access mode is read mode. We can also specify 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 containing non-textual data are opened in binary mode that means
read/write are performed in terms of bytes.
The below table shows various file access modes that can be used with the
open() method.
[Link] Page 3
Closing a file
Once we are done with the read/write operations on a file, it is a
good practice to close the file.
Python provides a close() function.
While closing a file, the system frees the memory allocated to it.
Syntax:
file_object.close()
Python makes sure that any unwritten or unsaved data is flushed
off (written) to the file before it is closed.
Opening a file using with clause
In Python, we can also open a file using with clause.
The advantage of using with clause is that any file that is opened using this
clause is closed automatically.
Syntax:
with open (file_name, access_mode) as file_object:
Example:
with open(“[Link]”,”r+”) as myObject:
content = [Link]()
Here, we don’t have to close the file explicitly using close() statement.
Python will automatically close the file.
[Link] Page 4
Writing to a Text File
For writing to a file, we first need to open it in write or append mode.
If we open an existing file in write mode, the previous data will be erased file
object will be positioned at the beginning of the 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.
The following methods to write data in the file.
• write() - for writing a single string
• writelines() - for writing a sequence of strings
The write() method
write() method takes a string as an argument and writes it to the text file. It
returns the number of characters being written on single execution of the
write() method. We need to add a newline character (\n) at the end of every
sentence to mark the end of line.
The write() actually writes data onto a buffer. When the close() method is
executed, the contents from this buffer are moved to the file located on the
permanent storage.
Example
[Link] Page 5
The writelines() method
This method is used to write multiple strings to a file. We need to pass an
iterable object like lists, tuple, etc. containing strings to the writelines()
method. ), the writelines() method does not return the number of characters
written in the file.
Reading from a Text File
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)
Consider the following set of statements to understand the usage of read()
method:
[Link] Page 6
If no argument or a negative number is specified in read(), the entire
file content is read. For example,
The readline([n]) method
This method reads one complete line from a file where each line terminates
with a newline (\n) character. It can also be used to read a specified number
(n) of bytes of data from a file but maximum up to the newline character
(\n).
[Link] Page 7
If no argument or a negative number is specified, it reads a complete line
and returns string.
The readlines() method
The method reads all the lines and returns the lines along with newline as a
list of strings. The followingexample uses readlines() to read data from the
text file [Link]
As shown in the above output, when we read a file using readlines()
function, lines in the file become members of a list, where each list element
ends with a newline character (‘\n’).
[Link] Page 8
In case we want to display each word of a line separately as an element of a
list, then we can use split() function. The following code demonstrates the
use of split() function.
[Link] Page 9
if splitlines() is used instead of split(), then each line is returned as element
of a list, as shown in the output below:
Writing and reading to a text file
In below example, the file named [Link] is opened in write mode and the
file handle named file is returned. The name is accepted from the user and
written in the file using write(). Then the file is closed and again opened in
read mode. Data is read from the file and displayed till the end of file is
reached.
[Link] Page 10
Setting Offsets in a File
So far we have accessed data sequentially from a file. If we want to access
data in a random fashion, then Python gives us seek() and tell() functions
to do so.
The tell() method: This function returns an integer that specifies the
current position of the file object in the file. The position so specified is the
byte position from the beginning of the file till the current position of the file
object.
Syntax:
file_object.tell()
[Link] Page 11
The seek() method: This method is used to position the file object at a
particular position in a file.
Syntax:
file_object.seek(offset [, reference_point])
In the above syntax, 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. The offset has to be counted. It 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, i.e. the offset is counted
from the beginning of the file.
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
To display data from a text file.
In below Program, the readline() is used in the while loop to read the data
line by line from the text file. The lines are displayed using the print(). As
the end of file is reached, the readline() will return an empty string. Finally,
the file is closed using the close().
[Link] Page 12
The pickle module
• 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 must be imported to load and dump data.
• The pickle module provides two methods - dump() and load() to work with
binary files for pickling and unpickling, respectively.
Serialization is the process of transforming data or an object in memory
(RAM) to a stream of bytes called byte streams. These byte streams in a
binary file can then be stored in a disk or in a database or sent through
a network. Serialization process is also called pickling.
De-serialization or unpickling is the inverse of pickling process where a
byte stream is converted back to Python object.
[Link] Page 13
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:
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.
[Link] Page 14
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:
Store_object = load(file_object
*****
[Link] Page 15