Chapter 5 FileHandlingFinal
Chapter 5 FileHandlingFinal
File Handling in
Python
Syllabus: (Class XII:CS 2022-23)
□ Introduction to files, types of files (Text file, Binary file, CSV
file), relative and absolute paths
□ Text file: opening a text file, text file open modes (r, r+, w,
w+, a, a+), closing a text file, opening a file using with
clause, writing/appending data to a text file using write()
and writelines(), reading from a text file using read(),
readline() and readlines(), seek and tell methods,
manipulation of data in a text file.
□ Binary file: basic operations on a binary file: open using file
open modes (rb, rb+, wb, wb+, ab, ab+), close a binary file,
import pickle module, dump() and load() method, read,
write/create, search, append and update operations in a
binary file.
□ CSV file: import csv module, open / close csv file, write into
a csv file using csv.writer() and read from a csv file using
csv.reader( )
Objective..
In this presentation you will learn about the basic
concepts and operations of File handling in Python
Programming language covering Text file, Binary
File and CSV file handling.
□ Introduction to files & File Handling
□ Various Operations on File
□ Handling Text Files
□ Handling Binary Files
□ Handling .CSV files
□ Applications of file
Introduction
In general, Python program accepts data from
keyboard and stores data in memory variables
temporarily. To store data permanently, we
have store data in data files on secondary
storage. Once the data stored in the files , we
can access data and reuse in the application.
FILE HANDLING is a mechanism by which we can
access and manipulate data files (create/read/
write/update) stored on secondary storage
media using Python programs and library
functions.
Data File & Python Program
Python
Program
Mostly .txt and .rtf are used May have any extension as
as extensions to text files. defined by the application.
Data File Handling in Python
OPENING FILE
We should first open the file for read or write
operation by specifying the name of file and
access mode.
PERFORMING READ/ WRITE OPEARTION
Once the file is opened, we can either read or
write data as per requirement, using various
library functions available in Python.
CLOSING FILE
After performing operation, we must close the
file and release the file for other application to
use it.
Opening a File
A file can be opened for read, write, append operation.
file_object = open(filename, mode)
Where file_object is file handler and mode represents
access mode of file. If mode is not given then default
mode is “read”
Example: myfile = open(“story.txt”)
In this example disk file “story.txt” is loaded in
memory for READ operation and its reference is linked
to “myfile” object.
It is assumed that “story.txt” is stored in the same
folder where .py file is stored otherwise, we have to
give full path (location) of the file.
Location of file: File PATH
▪ PATH is term which refers to location of file on the
storage media.
▪ A file Path can be written as –
DRIVE :\ FOLDER (DIRECTORY)\....\FILE.
▪ In general, the hard disk is logically divided into
many parts called DRIVES like C: , D: etc. The
drive is the main container which holds all Folders
and Files.
▪ Drive is also known as ROOT DIRECTORY.
▪ Drive contains Folder and Files.
▪ Folder contains sub-folders or files.
▪ Files are the actual data container.
Absolute Path & Relative Path
Absolute path is the full address of any file or folder
starting from the Drive i.e. from ROOT -
DriveName:\Folder1\Folder2\…..\filename
for e.g. the absolute path of file STORY.TXT may
be- C:\MyFolder\2022\June\STORY.TXT
Relative Path is the location of file/folder in respect of the
current folder. The following special symbols are used:
▪ Single Dot (.) : single dot (.) refers to current folder.
▪ Double Dot (..) : double dot (..) refers to parent folder
▪ Backslash (\) : backslash refers to ROOT folder.
for e.g. if absolute path of file STORY.TXT is
C:\MyFolder\2022\June\STORY.TXT and you are currently
working in 2022 folder then Relative path can be written as-
.\June\STORY.TXT
Opening File using PATH
In general, if path is not given the Python assumes
that file is to be created/accessed from location where
program file (.py) is kept. If data file is stored
elsewhere, we can specify path string.
myfile = open(“d:\\myFolder\\2022\\June\\Story.txt”)
‘a’ ‘ab’ Append File is in write mode only, new data will
be added to the end of existing data i.e.
no overwriting. If file not exists it is
created
‘r+’ ‘r+b’ Read and File must exists otherwise error is raised
‘rb+’ write Both reading and writing can take place
w+ ‘w+b’ Write and File is created if not exists, if exists data
‘wb+’ read will be truncated, both read and write
allowed
‘a+’ ‘a+b’ Write and Same as above but previous content will
‘ab+’ read be retained and both read and write.
Opening File using “With” Statement:
❖ Python’s “with” statement for file handling is very handy
when you have related operations which you would like
to execute as a block of code in between:
with open(filename[, mode]) as filehandle:
file_manipulation_statement
Example:
with open(“story.txt”, “w”) as mf:
mf.write(“Once upon a time”)
❖ The advantage of “with” clause is that it will
automatically close the file after executing the nested
block of code.
Closing file
When a data file is open, its reference or File
handle is stored on File_Object on which file
is opened. So, after performing operations
on the file, the data file must be closed.
A file can be closed using close() function
through its file handler object.
myfile.close()
Observe that
while writing
data to file using
“w” mode the
previous
SECOND RUN.. content of
existing file will
be overwritten.
should write
using “a” mode
i.e. append
mode
Example-2:
New content is
added after
previous content
Example-3: Using
writelines()
Example-4:Writing String as a record to file
Example-5: To copy the content of one file to another file.
Working with Binary files
▪ If we want to write a structured data such as
list or dictionary to a file and read it
subsequently, we need to handle Binary Files
using Python Pickle module.
▪ Pickling is the process of converting structure
to a byte stream before writing to a file.
▪ While reading the content of file a reverse
process called Unpickling is used to convert
the byte stream back to the original format.
Steps to perform binary file operations
myfile.csv
BEFORE
EXECUTION
myfile.csv
OUTP AFTER
UT EXECUTION
Writing record using writerow()
Writing records using writerows()
Searching Record in CSV File
Thanks…