Chapter – 5 (File Handling)
CSV Files – CSV stands for Comma Separated Values. CSV is just like a text file, in a human readable format which is
extensively used to store tabular data, in a spreadsheet or database. The separator character of CSV files is called a
delimiter. Default delimiter is comma (,). Other delimiters are tab (‘\t’), colon (:), pipe (|), semicolon (;) characters.
Advantages of CSV File –
1. Universal Use
2. Easy to understand
3. Quick to create
4. Large amount can store
Python csv module –csv module provides two types of objects:
1. reader –To read from CSV files.
2. writer – To write into the CSV files.
To import csv module in our program, write the following statement:
importcsv
Opening/ Closing csv files –
1. Open a CSV file –
f=open(“[Link]”, “w”)
or
f=open(“[Link]”, “r”)
2. Close a CSV file –
[Link]( )
Role of Argument newline in opening of csv files –Newline argument specifies how would Python handle new
line character while working with CSV files, on different operating system. Different operating systems store EOL
character differently. Addition optional argument as newline = '' with file open ( ) will ensure that no translation of
End of Line (EOL) character takes place.
Example – f = open ("[Link]", "w",newline='')
Writing in CSV files –We can use following functions to write in a CSV file:
1. [Link] ( ) –Returns a writer object which writes data into CSV files.
2. <writerobject>.writerow ( ) –Writes one tow of data on to the writer object.
Example –
importcsv
def create( ):
f=open("[Link]", "w", newline=' ')
f1=[Link](f)
[Link] (['Roll','Name','Total Marks'])
while True:
roll=int(input("Enter Roll no:"))
name=input("Enter name:")
total=int(input("Enter total Marks:"))
record=[roll,name,total]
[Link] (record)
ch=int(input("[Link] record\[Link]\nEnter your choice:"))
ifch==2:
break;
3. <writerobject>.writerows ( ) – Writes multiple rows on to the writer object.
Example –
importcsv
def create( ):
f=open("[Link]", "w", newline=' ')
f1=[Link](f)
[Link] (['Roll','Name','Total Marks'])
rec = [ ]
while True:
r=int (input ("Enter Roll no :"))
n=input ("Enter name :")
t=in t(input("Enter total Marks:"))
record = [r, n, t]
[Link] (record)
ch=int(input("[Link] record\[Link]\nEnter your choice:"))
ifch==2:
break;
[Link](rec)
Role of writer object –the [Link] ( ) functions returns a writer object that converts the user’s data into a
delimited string. This string can later be used to write into CSV files using writerow ( ) function or writerows ( )
function.
Reading from CSV files –To read data from a CSV file, reader function of csv module is used.
1. [Link] ( ) –Returns a reader object. It loads the data from CSV file into an iterable after parsing delimited
data.
Example –
def display():
f=open("[Link]", "r", newline='\r\n')
f1=[Link](f)
for i in f1:
print(i)
Question: Write a program to write and read data from CSV file consisting Item No, Item Name, Quantity and Price.
Write a function to search for a particular item using Item Code.
Import csv
def create( ):
f=open ("[Link]", "w", newline=' ')
f1=[Link] (f)
[Link] (['Item No', 'Item Name', 'Quantity', 'Price'])
rec = [ ]
while True:
no=int (input("Enter Item No:"))
name=input ("Enter Item Name:")
qty=int (input ("Enter Quantity:"))
price=float(input("Enter Price:"))
record=[no, name, qty, price]
[Link] (record)
ch=int(input("[Link] record\[Link]\nEnter your choice:"))
if ch==2:
break;
[Link] (rec)
def display( ):
f=open("[Link]", "r", newline='\r\n')
f1=[Link] (f)
for i in f1:
print (i)
def search( ):
f=open ("[Link]", "r", newline='\r\n')
s=input ("Enter the Item No for search")
print("Displaying record")
f1=[Link] (f)
next (f1)
for i in f1:
if i[0]==s:
print (i)
create( )
display( )
search( )
Binary Files –Most of the files that we see in our computer system are called binary files.
1. We can open some binary files in the normal text editor but we cannot read the content present inside the
file.
2. That’s because all the binary files will be encoded in the binary format, which can be understood only by a
computer or a machine.
3. In binary files, there is no delimiter to end a line.
4. Since they are directly in the form of binary, hence there is no need to translate them.
5. Binary files are easy and fast in working.
Example –
Image files: .png, .gif, .jpg, .bmp etc.
Video files: .mp4, .3gp, .mkv, .avi etc.
Audio files: .mp3, .wav, .mka, .aac, etc.
Archive files: .zip, .rar, .iso, .7z etc.
Executable files: .exe, .dll, .class etc.
Pickling and Unpickling –
Pickling – Pickling refer to the process of converting the structure (such as list or dictionary) to a byte stream before
writing to the file.
Structure (List Byte
or Dictionary) Pickling
Stream
Unpickling – Unpickling refer to the process of converting the byte steam back to the original structure.
Byte Structure (List
Pickling or Dictionary)
Stream
Pickle Module – Pickle module is used to store any kind of object in file as it allows us to store python objects with
their structure. So for storing data in binary format, we will use pickle module. First we need to import the module. It
provides two main methods for the purpose, dump and load.
Example –import pickle
1. [Link]( ) function – This function is used to write the object in a file.
Syntax – [Link](<Structure>, FileObject)
Note: Structure can be any sequence of Python. It can be either list or dictionary.
2. [Link]( ) function – This function is used to read data from a file.
Syntax – structure = [Link] (FileObject)
Note: Structure can be any sequence of Python. It can be either list or dictionary.
Example – import pickle
def write():
f=open("[Link]",'wb')
List=['comp','Math','English','Physics','Chemistry']
dic={'comp':100,'Math':98,'English':74,'Physics':40,'Chemistry':80}
[Link](List,f)
[Link](dic,f)
[Link]()
def read():
f=open("[Link]",'rb')
lst=[Link](f)
d=[Link](f)
print(lst)
print(d)
[Link]()
write()
read()
Example – Write a program to write and read multiple data from a binary file.
import pickle
def write():
f=open("[Link]",'wb')
record=[]
while True:
rno=int(input("Enter roll no:"))
name=input("Enter Name:")
marks=int(input("Enter Marks:"))
data=[rno,name,marks]
[Link](data)
ch=input("Dou you want to enter more records?(y/n)")
ifch=='n':
break
[Link](record,f)
defsimpleread():
f=open("[Link]",'rb')
s=[Link](f)
print(s)
write()
def read():
f=open("[Link]",'rb')
s=[Link](f)
for i in s:
rno=i[0]
name=i[1]
marks=i[2]
print(rno,name,marks)
simpleread()
read()
Random aces in File Handling –
1. seek()
2. tell()
1. seek() function – seek() function is used to change the position of the file handle (file pointer) to a given
specific position. File pointer is like a cursor, which defines from where the data has to be read or writer in
the file.
Syntax – [Link](offset, from_what)
Where f is file pointer.
“From_what” – The reference point is defined by the “from-what” argument. It have any of three values:
1. 0:sets the reference point at the beginning of the file, which is by default.
2. 1: sets the reference point at the current file position.
3. 1: sets the reference point at the end of the file.
Note: But in Python 3.x and above, we can seek from beginning only, if opened in text mode. We can
overcome from this by opening the file binary mode.
2. tellp() function – This function returns the position of current file pointer.
Syntax – <filepointer>.tell()
Example – f=open("[Link]","rb")
[Link](9)
[Link](-9,1)
print([Link](5))
print([Link]())
[Link](9,1)
print([Link](12))
print([Link]())
[Link](-9,2)
print([Link]())
print([Link]())
Write records in a binary file –
def write():
f=open("[Link]",'wb')
record=[ ]
while True:
rno=int(input("Enter roll no:"))
name=input("Enter Name:")
marks=int(input("Enter Marks:"))
data=[rno,name,marks]
[Link](data)
ch=input("Dou you want to enter more records?(y/n)")
ifch=='n':
break
[Link](record,f)
Read records from a binary file –
def read():
f=open("[Link]","rb")
while True:
try:
s=[Link](f)
for i in s:
print(i)
exceptEOFError:
break
[Link]()
Search a record in a binary file –
def search():
f=open("[Link]",'rb')
s=[Link](f)
found=0
rno=int(input("Enter the roll no whose record you want to search"))
for i in s:
if i[0]==rno:
print(i)
found=1
if found==0:
print("Record not found")
else:
print("Record found")
Update a record in a binary file –
def update():
f=open("[Link]",'rb+')
s=[Link](f)
found=0
rno=int(input("Enter the roll no whose record you want to update"))
for i in s:
ifrno==i[0]:
print("Current name:",i[1])
i[1]=input("Enter the updated name")
found=1
break
if found==0:
print("Record not found")
else:
[Link](0)
[Link](s,f)
Append records in a binary file –
def append():
f=open("[Link]",'ab')
record=[ ]
while True:
rno=int(input("Enter roll no:"))
name=input("Enter Name:")
marks=int(input("Enter Marks:"))
data=[rno,name,marks]
[Link](data)
ch=input("Dou you want to enter more records?(y/n)")
ifch=='n':
break
[Link](record,f)