0% found this document useful (0 votes)
22 views67 pages

3b.file hadling online_ binary

The document provides an overview of binary files and their handling in Python, including the concepts of pickling and unpickling using the pickle module. It explains how to create, read, and write binary files, as well as the serialization and deserialization processes. Additionally, it includes examples and exercises for practical implementation of these concepts.

Uploaded by

Ishaan Gupta
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)
22 views67 pages

3b.file hadling online_ binary

The document provides an overview of binary files and their handling in Python, including the concepts of pickling and unpickling using the pickle module. It explains how to create, read, and write binary files, as well as the serialization and deserialization processes. Additionally, it includes examples and exercises for practical implementation of these concepts.

Uploaded by

Ishaan Gupta
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/ 67

BINARY FILES

"Binary" files are any files where the format


isn't made up of readable characters.

Binary files can range from image files like


WHAT JPEGs or GIFs or audio files or word files etc

ARE Files will open in appropriate softwares like


photoshop, word etc
BINARY
FILES? Data type is preserved in binary file

There are not EOF characters


To open a file in binary mode
“b” is added to the mode

Creating f=open("file.txt","wb")
Binary f=open("file.dat",“wb")
Files in f=open('file1.xyz',’rb')
Python
f=open('file1.txt’, ‘ab+’)
PICKELING AND UNPICKLING USING
PICKEL MODULE
PICKELING AND UNPICKLING USING
PICKEL MODULE

Use the python module pickle for


structured data such as list or directory to a
file.
PICKLING refers to the process of
converting the structure to a byte stream
before writing to a file.
while reading the contents of the file,
a reverse process called UNPICKLING is used
to convert the byte stream back to the
original structure.
PICKELING AND UNPICKLING USING
PICKEL MODULE

First we need to import the module, It


provides two main methods for the purpose:-

1) dump() method
2) load() method
pickle.dump() Method

Use pickle.dump() method to write the


object in file which is opened in binary access
mode.

Syntax of dump method is:

dump(object,fileobject)
load(fileobject)
pickle.dump() Method
pickle.dump() Method

# A program to write list sequence in a


binary file
pickle.dump() Method

OUTPUT
pickle.dump() Method

Once you try to open list.dat file in


python editor to see the content python
generates decoding error.
pickle.load() Method
pickle.load() Method

pickle.load() method is used to read the


binary file.
pickle.load() Method

pickle.load() method is used to read the


binary file.
Writing into Binary files (Pickling)

• Pickle module is used to handle binary files

import pickle
f=open("file1.txt","wb")
d={1:"apple",2:"mango"}
pickle.dump(d,f) Dump writes the object d in file object f
Writing into Binary files

Writing Multiple type of data into binary files

import pickle
f=open("file1.txt","wb")
a="New thing"
l=[10,20,30,40]
d={1:"apple",2:"mango"}
pickle.dump(a,f)
pickle.dump(l,f)
pickle.dump(d,f)
f.close()
Reading data from a binary file (Unpickling)

• Simple reading
import pickle
f=open("file1.txt","rb")
m=pickle.load(f)
print(m,type(m))
n=pickle.load(f)
print(n,type(n))
o=pickle.load(f) Load method returns object data from the pickled file
print(o,type(o))
How to read data from binary file where no of records are not known

while(True) - Infinite loop


Exception handled
EOFError
How to read data from binary file where no of records are not known

while(True) - Infinite loop

Exception handled
EOFError
Serialization

The pickle module is used for implementing binary protocols for serializing
and de-serializing a Python object structure.

• “Pickling” is the process whereby a Python object hierarchy is converted into


a byte stream
• “Unpickling” is the inverse operation, whereby a byte stream (from a binary
fileor bytes-like object) is converted back into an object hierarchy.
Application of pickle module
Task
1) UDF to Save dictionary object containing {RNO, Name, Marks} to a
pickled file student.txt
2) UDF Read all objects from file student.txt
3) Implement menu driven program to achieve above
1) UDF Save dictionary object containing {RNO,
Name, Marks} to a pickled file student.txt
import pickle
def writefile():
d={}
fobj=open("student.txt","ab")
d["rno"]=int(input('Enter the rno'))
d["name"]=input('Enter the name')
d["marks"]=int(input('Enter the marks'))
pickle.dump(d,fobj)
fobj.close()
2) UDF Read all objects from file student.txt

def readdata():
f=open("student.txt","rb")
while(True):
try:
obj=pickle.load(f)
print(obj)
except EOFError:
f.close()
break
3) Implement menu driven

def menu(): ch=int(input('Enter the choice'))


while(True): if(ch==1):
print("1: Write data") writefile()
print("2: Read data") elif(ch==2):
print("3: Exit") readdata()
elif(ch==3):
break
menu()
Complete program Output
Recap
1) The process of pickling in Python includes:
A) conversion of list into a database
B) conversion of byte stream into object hierarchy
C) conversion of a Python object hierarchy into byte stream
D)conversion of a datatable into a list
Recap
2) The method _____________ allows serialize a data stream

3) Differentiate between write() and dump() methods?

4) Differentiate between load() and read() methods?


SEARCH BY ROLL NO
UPDATE RECORD

[{ },{ },{ }…]


[( ),( ),( )]
[[ ], [ ], [ ]]
• RECORD FOUND OR
NOT
• IF FOUND, DO YOU
WANT TO UPDATE
• IF YES THEN UPDATE
• OTHERWISE DON’T DO
ANYTHING TO THE
FILE
UPDATE RECORD
DELETE RECORD
Complete program having all 5 operations(5.py) to be shared
import pickle record is to be updated")) f.close()
def writefile(): f = open('student.txt','wb')
fobj=open("student.txt","ab") while True: for x in reclst:
d={} try: if x['rno']==r:
d["rno"]=int(input('Enter the rno')) rec = pickle.load(f) continue
d["name"]=input('Enter the name') reclst.append(rec) else:
d["marks"]=int(input('Enter the except EOFError: pickle.dump(x,f)
marks')) break f.close()
pickle.dump(d,fobj) f.close() print("now file contains")
fobj.close() flag=False f=open("student.txt","rb")
ans='n' while(True):
def readdata(): for i in range (len(reclst)): try:
f=open("student.txt","rb") if reclst[i]['rno']==r: obj=pickle.load(f)
while(True): flag=True print(obj)
try: print("old record") except EOFError:
obj=pickle.load(f) print(reclst[i]) f.close()
print(obj) ans=input("are u sure of break
except EOFError: updating this record(y/n)")
f.close() if ans.lower()=='y':
break m=eval(input("enter correct def menu():
def search_rno(): marks")) while(True):
import pickle reclst[i]['marks'] = m print("1: Write data")
f = open('student.txt','rb') if ans=='y': print("2: Read data")
Note:
negative indexing
works only with binary
files
PRACTICE : BINARY FILE OPERATIONS

Q1. Following is the structure of each record in a


data file named ”PRODUCT.DAT”.
{"prod_code":value,
"prod_desc":value,
"stock":value}
The values for prod_code and prod_desc are
strings, and the value for stock is an integer.
Write a function in PYTHON to update the file with
a new value of stock. The stock and the
product_code, whose stock is to be updated, are to
be input during the execution of the function.
PRACTICE : BINARY FILE OPERATIONS
import pickle break
def update(): if flag==False:
cd=input("enter product code whose stock is to be print("product code not found")
updated") else:
f=open("product.dat",'rb') f=open("product.dat",'wb')
flag=False for rec in rec_list:
rec_list=[] pickle.dump(rec,f)
while True: print("record updated")
try: f.close()
rec=pickle.load(f)
rec_list.append(rec)
except EOFError:
f.close()
break
for i in range(len(rec_list)):
if rec_list[i]['code']==cd:
flag=True
rec_list[i]['stock']=int(input("enter new value
of stock"))
def enter_data(): except EOFError:
d={} break
f=open("product.dat",'ab') f.close()
pc=input("enter product code")
pd=input("enter product description") #driver code
st=int(input("enter stock")) while True:
d['code']=pc print("\n1: Enter record")
d['desc']=pd print("\n2: Display all")
d['stock']=st print("\n3: Update record")
pickle.dump(d,f) print("\n0: Exit")
f.close() ch=int(input("\nEnter choice"))
print("record inserted") if ch==1:
enter_data()
elif ch==2:
def disp_all(): disp_all()
f=open("product.dat",'rb') elif ch==3:
while True: update()
try: elif ch==0:
rec=pickle.load(f) break
print(rec)
PRACTICE : BINARY FILE OPERATIONS

Q2. Given a binary file “STUQ2.DAT”, containing records of


the following type:
{‘S_Admno’:value, ‘S_Name’:value, ‘Percentage’:value}
Where these three values are:
S_Admno – Admission Number of student (string)
S_Name – Name of student (string)
Percentage – Marks percentage of student (float)
Write a function in PYTHON that would read contents of the
file “STUDENT.DAT” and display the details of those
students whose percentage is above 75.
PRACTICE : BINARY FILE OPERATIONS
PRACTICE : BINARY FILE OPERATIONS

import pickle d['perc']=pr print("\n0: Exit")


def distinction(): pickle.dump(d,f) ch=int(input("\nEnter choice"))
f=open("stuq2.dat",'rb') f.close() if ch==1:
flag=False print("record inserted") enter_data()
rec={} elif ch==2:
while True: disp_all()
try: def disp_all(): elif ch==3:
rec=pickle.load(f) f=open("stuq2.dat",'rb') distinction()
if rec['perc']>=75: while True: elif ch==0:
print(rec) try: break
except EOFError: rec=pickle.load(f)
f.close() print(rec)
break except EOFError:
break
def enter_data(): f.close()
d={}
f=open("stuq2.dat",'ab') #driver code
ad=input("enter admn no") while True:
nm=input("enter stu name") print("\n1: Enter record")
pr=int(input("enter perc")) print("\n2: Display all")
d['adm']=ad print("\n3: display distinction
d['name']=nm holders")
PRACTICE : BINARY FILE OPERATIONS

Q2a. Given a binary file “STUQ2.DAT”, containing records


of the following type:
[S_Admno, S_Name, Percentage]
Where these three values are:
S_Admno – Admission Number of student (string)
S_Name – Name of student (string)
Percentage – Marks percentage of student (float)
Write a function in PYTHON that would read contents of the
file “STUDENT.DAT” and display the details of those
students whose percentage is above 75.
PRACTICE : BINARY FILE OPERATIONS
PRACTICE : BINARY FILE OPERATIONS

import pickle pr=int(input("enter perc")) print("\n1: Enter record")


def distinction(): L=[ad,nm,pr] print("\n2: Display all")
f=open("stuq2_list.dat",'rb') pickle.dump(L,f) print("\n3: display distinction holders")
flag=False f.close() print("\n0: Exit")
rec=[] print("record inserted") ch=int(input("\nEnter choice"))
while True: if ch==1:
try: enter_data()
rec=pickle.load(f) def disp_all(): elif ch==2:
if rec[2]>=75: f=open("stuq2_list.dat",'rb') disp_all()
print(rec) while True: elif ch==3:
except EOFError: try: distinction()
f.close() rec=pickle.load(f) elif ch==0:
break print(rec) break
except EOFError:
def enter_data(): break
L=[] f.close()
f=open("stuq2_list.dat",'ab')
ad=input("enter admn no") #driver code
nm=input("enter stu name") while True:
PRACTICE : BINARY FILE OPERATIONS

Q3. Assuming the tuple Vehicle as follows:


( vehicletype, no_of_wheels)
Where vehicletype is a string and no_of_wheels is an
integer.
Write a function showfile() to read all the records present
in an already existing binary file SPEED_tuple.DAT and
display them on the screen, also count the number of
records present in the file.
PRACTICE : BINARY FILE OPERATIONS
PRACTICE : BINARY FILE OPERATIONS

import pickle ctr=0 print("\n3: display distinction


while True: holders")
def enter_data(): try: print("\n0: Exit")
T=() rec=pickle.load(f) ch=int(input("\nEnter
f=open("speed_tuple.dat",'ab') print(rec) choice"))
vt=input("enter vehicle type") ctr+=1 if ch==1:
now=int(input("enter no. of except EOFError: enter_data()
wheels")) break elif ch==2:
T=(vt,now) f.close() showfile()
pickle.dump(T,f) print("No. of records elif ch==0:
f.close() read:",ctr) break
print("record inserted")
#driver code
while True:
def showfile(): print("\n1: Enter record")
f=open("speed_tuple.dat",'rb') print("\n2: Display all")
PRACTICE : BINARY FILE OPERATIONS

Q4. Write a function in PYTHON to search for a


BookNo from a binary file “BOOK_dict.DAT”,
assuming the binary file is containing the records of
the following type:
{"BookNo":value, "Book_name":value}
Assume that BookNo is an integer.
PRACTICE : BINARY FILE OPERATIONS
PRACTICE : BINARY FILE OPERATIONS
import pickle print("book number not break
def search(): found") f.close()
bn=input("enter book number
whose details are to be searched") def enter_data(): #driver code
f=open("book_dict.dat",'rb') d={} while True:
flag=False f=open("book_dict.dat",'ab') print("\n1: Enter record")
rec_list=[] bno=input("enter book number") print("\n2: Display all")
while True: bn=input("enter book name") print("\n3: Search book no")
try: d['BookNo']=bno print("\n0: Exit")
rec=pickle.load(f) d['Book_name']=bn ch=int(input("\nEnter choice"))
rec_list.append(rec) pickle.dump(d,f) if ch==1:
except EOFError: f.close() enter_data()
f.close() print("record inserted") elif ch==2:
break disp_all()
for i in range(len(rec_list)): def disp_all(): elif ch==3:
if rec_list[i]['BookNo']==bn: f=open("book_dict.dat",'rb') search()
flag=True while True: elif ch==0:
print(rec_list[i]) try: break
break rec=pickle.load(f)
f.close() print(rec)
if flag==False: except EOFError:
PRACTICE : BINARY FILE OPERATIONS

Q5. Assuming that a binary file


VINTAGE.DAT contains records of the
following type, write a function in PYTHON
to read the data VINTAGE.DAT and display
those vintage vehicles, which are priced
between 200000 and 250000.
[VNO, VDesc, price]
PRACTICE : BINARY FILE OPERATIONS
PRACTICE : BINARY FILE OPERATIONS
import pickle vn=int(input("enter vehicle no")) f.close()
def disp_price_range(): vd=input("enter vehicle
f=open("vintage.dat",'rb') description") #driver code
flag=False pr=eval(input("enter price")) while True:
rec=[] L=[vn,vd,pr] print("1: Enter record")
while True: pickle.dump(L,f) print("2: Display all")
try: f.close() print("3: display according to
rec=pickle.load(f) print("record inserted") range")
if print("0: Exit\n")
200000<=rec[2]<=250000: ch=int(input("\nEnter choice"))
print(rec) def disp_all(): if ch==1:
except EOFError: f=open("vintage.dat",'rb') enter_data()
f.close() while True: elif ch==2:
break try: disp_all()
rec=pickle.load(f) elif ch==3:
def enter_data(): print(rec[0],rec[1],rec[2]) disp_price_range()
L=[] except EOFError: elif ch==0:
f=open("vintage.dat",'ab') break break
PRACTICE : BINARY FILE OPERATIONS

Q6. Write a function in PYTHON to search for a


laptop from a binary file “LAPTOP.DAT”
containing the records of following type. The user
should enter the model number and the function
should display the details of the laptop.
[ModelNo, RAM, HDD, Details]
where ModelNo, RAM, HDD are integers, and
Details is a string.
PRACTICE : BINARY FILE OPERATIONS
PRACTICE : BINARY FILE OPERATIONS
import pickle f=open("laptop.dat",'ab')
def disp_model_details(): mn=int(input("enter model no")) #driver code
f=open("laptop.dat",'rb') rm=int(input("enter RAM")) while True:
flag=False hd=int(input("enter HDD")) print("1: Enter record")
rec=[] det=input("enter details") print("2: Display all")
m=int(input("enter model no to be print("3: display according to
searched")) L=[mn,rm,hd,det] range")
while True: pickle.dump(L,f) print("0: Exit\n")
try: f.close() ch=int(input("\nEnter choice"))
rec=pickle.load(f) print("record inserted") if ch==1:
if rec[0]==m: enter_data()
print(rec) def disp_all(): elif ch==2:
flag=True f=open("laptop.dat",'rb') disp_all()
except EOFError: while True: elif ch==3:
f.close() try: disp_model_details()
break rec=pickle.load(f) elif ch==0:
if flag==False: print(rec[0],rec[1],rec[2],rec[3]) break
print("invalid model number") except EOFError:
def enter_data(): break
L=[] f.close()
PRACTICE : BINARY FILE OPERATIONS

Q7. Write a function in PYTHON to


search for the details (Number and Calls)
of those mobile phones which have more
than 1000 calls from a binary file
“mobile.dat”. Assuming that this binary
file contains records of the following type:
(Number,calls)
PRACTICE : BINARY FILE OPERATIONS
PRACTICE : BINARY FILE OPERATIONS

import pickle calls made")) #driver code


T=(mn,noc) while True:
def search_file(): pickle.dump(T,f) print("1: Enter record")
f=open("mobile.dat",'rb') f.close() print("2: Display all")
while True: print("record inserted") print("3: display deatils for
try: calls more than 1000")
rec=pickle.load(f) print("0: Exit")
if rec[1]>1000: def showfile(): ch=int(input("\nEnter
print(rec) f=open("mobile.dat",'rb') choice"))
except EOFError: ctr=0 print('\n')
break while True: if ch==1:
f.close() try: enter_data()
rec=pickle.load(f) elif ch==2:
def enter_data(): print(rec) showfile()
T=() except EOFError: elif ch==3:
f=open("mobile.dat",'ab') break search_file()
mn=input("enter mobile f.close() elif ch==0:
PRACTICE : BINARY FILE OPERATIONS

Q8. Write a function in PYTHON to read the


records from binary file GAMES.DAT and
display the details of those games, which are
meant for children of AgeRange “8 to 13”.
Assume that the file GAMES.DAT contains
records of the following type:
[GameCode, GameName, AgeRange]
PRACTICE : BINARY FILE OPERATIONS
PRACTICE : BINARY FILE OPERATIONS
import pickle gn=input("enter game name") while True:
def show_age_range(): ar=input("enter age range") print("1: Enter record")
f=open("games.dat",'rb') L=[gc,gn,ar] print("2: Display all")
flag=False pickle.dump(L,f) print("3: display games of age
rec=[] f.close() range 8 to 13")
while True: print("record inserted") print("0: Exit")
try: ch=int(input("\nEnter choice"))
rec=pickle.load(f) def disp_all(): print('\n')
if rec[2]=="8 to 13": f=open("games.dat",'rb') if ch==1:
print(rec) while True: enter_data()
except EOFError: try: elif ch==2:
f.close() rec=pickle.load(f) disp_all()
break print(rec) elif ch==3:
except EOFError: show_age_range()
def enter_data(): break elif ch==0:
L=[] f.close() break
f=open("games.dat",'ab')
gc=input("enter game code") #driver code
PRACTICE : BINARY FILE OPERATIONS

Q9. Write a function in PYTHON to read each


record of a binary file ITEMS.DAT, find and
display those items which costs less than 2500.
Assume that the file ITEMS.DAT is created
with the help of objects of the following type:
{"ID":string, "GIFT":string,
"Cost":integer}
PRACTICE : BINARY FILE OPERATIONS
PRACTICE : BINARY FILE OPERATIONS
import pickle except EOFError:
def search(): def enter_data(): break
f=open("items_q9.dat",'rb') d={} f.close()
flag=False f=open("items_q9.dat",'ab')
rec_list=[] gid=input("enter Gift ID") #driver code
while True: gn=input("enter Gift name") while True:
try: pr=int(input("enter price")) print("1: Enter record")
rec=pickle.load(f) d['ID']=gid print("2: Display all")
rec_list.append(rec) d['GIFT']=gn print("3: Search items whose cost is
except EOFError: d['Cost']=pr less than 2500")
f.close() pickle.dump(d,f) print("0: Exit")
break f.close() ch=int(input("\nEnter choice"))
for i in range(len(rec_list)): print("record inserted") if ch==1:
if rec_list[i]['Cost']<2500: enter_data()
flag=True def disp_all(): elif ch==2:
print(rec_list[i]) f=open("items_q9.dat",'rb') disp_all()
break while True: elif ch==3:
f.close() try: search()
if flag==False: rec=pickle.load(f) elif ch==0:
print("not found") print(rec) break
PRACTICE : BINARY FILE OPERATIONS

Q10. Write a definition for function BUMPER() in


PYTHON to read each object of a binary file
ITEMS.DAT, find and copy details of those items, whose
cost is less than 2000 to the file “discount.dat”. Assume
that the file ITEMS.DAT is created with the help of
objects of the following type:
{"ID":string, "GIFT":string, "Cost":integer}
Display the contents of the file “items.dat” and
“discount.dat”
PRACTICE : BINARY FILE OPERATIONS
PRACTICE : BINARY FILE OPERATIONS
import pickle disp_all("items_q9.dat") rec=pickle.load(f)
def BUMPER(): disp_all("discount.dat") print(rec)
fr=open("items_q9.dat",'rb') except EOFError:
def search():
fw=open("discount.dat",'wb') f=open("items_q9.dat",'rb')
flag=False
break
flag=False rec_list=[]
while True: f.close()
try:
rec_list=[] rec=pickle.load(f)
rec_list.append(rec)
while True: except EOFError: #driver code
f.close()
break while True:
try: for i in range(len(rec_list)):
if rec_list[i]['Cost']<2500:
print("1: Enter record")
rec=pickle.load(fr) flag=True
print(rec_list[i])
print("2: Display all")
break print("3: Search items whose cost is less than 2500")
rec_list.append(rec) f.close()
if flag==False: print("4: Copy items whose cost is less than 2000")
except EOFError: print("not found")
print("0: Exit")
def enter_data(): ch=int(input("\nEnter choice"))
fr.close() d={}
f=open("items_q9.dat",'ab') if ch==1:
break gid=input("enter Gift ID")
gn=input("enter Gift name") enter_data()
pr=int(input("enter price"))
for i in range(len(rec_list)): d['ID']=gid
elif ch==2:
d['GIFT']=gn fname=input("name of file whose contents are to
if rec_list[i]['Cost']<2000: d['Cost']=pr
pickle.dump(d,f) shown")
f.close()
flag=True print("record inserted") disp_all(fname)
elif ch==3:
pickle.dump(rec_list[i],fw) def disp_all(fname): search()
fr.close() f=open(fname,'rb') elif ch==4:
BUMPER()
if flag==False: print("details of file",f.name) elif ch==0:
print("not found") while True: break
fw.close()

You might also like