0% found this document useful (0 votes)
32 views26 pages

File Handling

The document covers file handling in Python, including operations for reading, writing, and appending to text and binary files. It explains various file access modes, how to open and close files, and methods for reading and writing data. Additionally, it introduces the pickle module for serializing and deserializing objects in binary files.

Uploaded by

Sooraj Rajmohan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views26 pages

File Handling

The document covers file handling in Python, including operations for reading, writing, and appending to text and binary files. It explains various file access modes, how to open and close files, and methods for reading and writing data. Additionally, it introduces the pickle module for serializing and deserializing objects in binary files.

Uploaded by

Sooraj Rajmohan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Further Programming

20.2 File Handling

Computer Science 9618


20.2 File Handling – Text File
Candidates should be able to:
• Write code to perform file-processing operations
• Open (in read, write, append mode) and close a file Read a
record from a file and write a record to a file
• Perform file-processing operations on serial, sequential,
random files

Computer Science 9618 2


20.2 File Handling – Text File

Reading and Writing to text files in Python


Python provides inbuilt functions for creating, writing and reading files. There are
two types of files that can be handled in python, normal text files and binary files
(written in binary language,0s and 1s).
•Text files: In this type of file, Each line of text is terminated with a special character
called EOL (End of Line), which is the new line character (‘\n’) in python by default.
•Binary files: In this type of file, there is no terminator for a line and the data is
stored after converting it into machine understandable binary language.

Computer Science 9618 3


20.2 File Handling – Text File

File Access Modes


Access modes govern the type of operations possible in the
opened file. It refers to how the file will be used once its opened.
These modes also define the location of the File Handle in the file.
File handle is like a cursor, which defines from where the data has
to be read or written in the file. There are 6 access modes in
python.

Computer Science 9618 4


20.2 File Handling – Text File

File Access Modes


Read Only (‘r’) : • Open text file for reading.
• The handle is positioned at the beginning of the file. If the file
does not exists, raises I/O error.
• This is also the default mode in which file is opened.
Read and Write (‘r+’) : • Open the file for reading and writing.
• The handle is positioned at the beginning of the file. Raises I/O
error if the file does not exists.
Write Only (‘w’) : • Open the file for writing.
• For existing file, the data is truncated and over-written.
• The handle is positioned at the beginning of the file.
• Creates the file if the file does not exists.
Write and Read • Open the file for reading and writing.
(‘w+’) : • For existing file, data is truncated and over-written.
• The handle is positioned at the beginning of the file.

Computer Science 9618 5


20.2 File Handling – Text File

File Access Modes


Append Only (‘a’) : • Open the file for writing.
• The file is created if it does not exist.
• The handle is positioned at the end of the file.
• The data being written will be inserted at the end, after the
existing data.
Append and Read (‘a+’) : • Open the file for reading and writing.
• The file is created if it does not exist.
• The handle is positioned at the end of the file.
• The data being written will be inserted at the end, after the
existing data.

Computer Science 9618 6


20.2 File Handling – Text File

Opening a file
It is done using the open() function. No module is required to be imported for this function.

• The file should exist in the same directory as the python program file else, full address of the file
should be written on place of filename.

Here, file1 is created as object for


MyFile1 and file2 as object for
MyFile2

Computer Science 9618 7


20.2 File Handling – Text File

Closing a file
close() function closes the file and frees the memory space acquired by that file. It is used at
the time when the file is no longer needed or if it is to be opened in a different file mode.

Computer Science 9618 8


20.2 File Handling – Text File

Writing to a file
There are two ways to write in a file.
1. write() : Inserts the string str1 in a single line in the text file.

2. writelines() : For a list of string elements, each string is inserted in


the text file. Used to insert multiple strings at a single time.

Computer Science 9618 9


20.2 File Handling – Text File
Reading from a file
There are three ways to read data from a text file.
read() : Returns the read bytes in form of a string. Reads n bytes, if no n
specified, reads the entire file.
Note: ‘\n’ is treated as a special character
of two bytes

readline() : Reads a line of the file and returns in form of a string. For specified n, reads
at most n bytes. However, does not reads more than one line, even if n exceeds the
length of the line.

readlines() : Reads all the lines and return them as each line a string element in a list.

Computer Science 9618 10


20.2 File Handling – Text File
Sample Programs

Computer Science 9618 11


20.2 File Handling – Text File
Sample Programs

Computer Science 9618 12


20.2 File Handling – Text File
Appending to a file

Computer Science 9618 13


20.2 File Handling – Text File
Appending to a file

Computer Science 9618 14


20.2 File Handling – Text File
Reading Word by word by using FOR loop

Computer Science 9618 15


20.2 File Handling – Text File
Read character by character using for loop

Computer Science 9618 16


20.2 File Handling – Text File
Read character by character using for loop

Computer Science 9618 17


20.2 File Handling – Binary File
Candidates should be able to:
• Write code to perform file-processing operations
• Open (in read, write, append mode) and close a file Read a
record from a file and write a record to a file
• Perform file-processing operations on serial, sequential,
random files

Computer Science 9618 18


20.2 File Handling – Binary File
Candidates should be able to:
• Write code to perform file-processing operations
• Open (in read, write, append mode) and close a file Read a
record from a file and write a record to a file
• Perform file-processing operations on serial, sequential,
random files

Computer Science 9618 19


Computer Science 9618 20
Getting & Resetting the Files Position

• The tell() method of python tells us the current position


within the file.
• The seek(offset[, from]) method changes the current file
position.
• If from is 0, the beginning of the file to seek.
• If it is set to 1, the current position is used .
• If it is set to 2 then the end of the file would be taken as
seek position.
• The offset argument indicates the number of bytes to be
moved.

Computer Science 9618 21


Binary file using pickle module

Python has a module which will help us and is


extremely easy to use. This module is called pickle; it
provides us with the ability to serialize and deserialize
objects, i.e., to convert objects into bitstreams which
can be stored into files and later be used to reconstruct
the original objects.

Computer Science 9618 22


Binary file using pickle module

Python has a module which will help us and is


extremely easy to use. This module is called pickle; it
provides us with the ability to serialize and deserialize
objects, i.e., to convert objects into bitstreams which
can be stored into files and later be used to reconstruct
the original objects.

Computer Science 9618 23


Binary file using pickle module

pickle.dump() function is used to store the object


data to the file. It takes 2 arguments. First
argument is the object that we want to store. The
second argument is the file object we get by
opening the desired file in write-binary (wb)
mode. pickle. dump(sob, ofile)

Any data structure or class object File handler object

Computer Science 9618 24


Binary file using pickle module

pickle.load()

pickle.load() function is used to retrieve pickled


data.The steps are quite simple. We have to use
pickle.load() function to do that. The primary
argument of pickle load function is the file object
that you get by opening the file in read-binary
(rb) mode. sob=pickle. load(ofile)

Any data structure or class object File handler object

Computer Science 9618 25


Binary file using pickle module
Example Program

Computer Science 9618 26

You might also like