Binary File Handling

Download as pdf or txt
Download as pdf or txt
You are on page 1of 66

Binary File

Processing
Binary File Processing
In Python a set of logically related data items, describing an entity is
stored as one unit in objects like dictionary, tuples, list.
Since these objects have some structure or hierarchy associated with it,
it is important that they are stored in a way that their original structure
and hierarchy is maintained.
A binary file in Python contains information in the same format in which
the information is held in memory i.e. the file content is stored without
any translations or encoding.
As the content in a Binary file is stored without any translation, It is not
readable when it is opened in a text editor.
Features Of Binary File
● As in Binary file raw data is stored without any translation, hence
while manipulating the binary file, the raw data read from the file
should be stored in objects of correct data type in the program.
● As a binary file stores the data in the same format as the object, It
is not readable when it is opened in a text editor.
● Binary file is much more compact then Text file. As no translation
occur in a Binary file, manipulation (reading and writing) of Binary
files are faster and easier than text files.
● Binary files are application program dependent i.e it can only be
opened and manipulated using the programming language which is
used to create it .
Features Of Binary File
● In Binary file (unlike Text file), no delimiter is used to end a line.
● As no translations occur in a binary file, these files are faster for the
application program to read and write than text files.
● In Python, files are opened in text mode by default. So to open files in
binary mode, when specifying the file opening mode, b is added to it.
● For example, read mode will become rb, write mode will become wb,
append mode will become ab and read-write mode will become rb+,
wb+ and ab+
Serialization & De-serialization
● Serialization is the process of transforming data stored in an object
to a stream of bytes called byte streams so that, it can be written
into a file.
● These byte streams in a binary file can then be stored in a disk.
● Serialization process, is also called pickling.
● Pickling or serialization converts an object in such a way that, it can
be reconstructed in original form, when it is retrieved from the file.
De-serialization or unpickling is the inverse of pickling process where a
byte stream is converted back to Python object. Unpickling produces
the exact replica of the original object.
Pickle Module
● Python pickle module, is used for serializing and Deserializing of a
Python object structure so that object can be stored and read from a
Binary file.
● In order to work with pickle module, it is required to include it in the
Python application by using import statement.
● To import pickle module, the statement is
import pickle
Binary file Processing
The process of manipulating Binary file is similar to other file
processing The Binary File Processing follows the steps of
open -> process ->close operation.

The steps for Binary file operation –


1. import pickle module.
2. open binary file in the required mode.
3. Process binary file by reading/writing objects using pickle
module’s methods.
4. close the file.
Binary file Processing
Opening Binary File
A binary file is opened using open() function
Syntax : file_object = open(file_name, mode)
- The file name is the name of the Binary file.
- The file opening mode must include b to ensure that file is opened in
binary mode.
- mode can be wb/wb+ for opening the file for writing, rb/rb+ for
opening the file in reading mode, ab/ab+ for reading mode
- The open() returns the file object/file handle to manipulate Binary file.

Example : fobj = open('data.dat','wb')


Binary file Processing
The open() opens the binary file data.dat in Writing Mode and returns
the file object which get assigned to fobj .
Alternatively the Binary file can also be opened using open() and with
statement
Syntax : with open(file_name, mode) as file_object :
Binaryfile manipulation Statements
Example : with open('data.dat','wb') as fobj:
Binaryfile manipulation Statements
Closing Binary File
The close() function used with the file handle is used to close the Binary
file. Any file manipulation, cannot be performed on closed file.
Syntax : file_object.close()
Example : fobj.close()
Writing data to a Binary file
● To write data into a Binary file, the file should be opened in
writing mode(wb/wb+ or ab/ab+).
● The file mode wb will always create a new file i.e if the file
already exists, wb/wb+ will over write the file.
● The ab mode will open the file in appending mode i.e the data
will be added to the existing content.
● In order to write an object into the binary file, dump() method
of pickle module is used
Writing data to a Binary file
dump() method
The dump() method of pickle module is used to write an object
into the binary file.
The file in which data are to be dumped, needs to be opened in
binary-write mode (wb).
Syntax : pickle.dump(data_object, file_object)
● data_object is the object whose content has to be
written/dumped to the file
● file handle is the object returned by open() while opening the
desired binary file
Writing data to a Binary file
Example : Write a program to write a record of a student (roll_no, name,
percentage and stream) in the binary file student.dat.
Program: import pickle
fobj = open("student.dat", "wb")
studrec = [1,"Rakesh",89, "Science"] #record as list object
pickle.dump(studerec, fobj) #Studrec dumped into
student.dat
fobj.close()
● The pickle module is included in the binary file using import statement
● The Binary file student.dat is opened in Write-Binary mode.
● The list object studrec is written into the file using dump() method.
Writing record as List object to a Binary file
Example : Write a program to create a binary file student.dat by accepting
students records (roll_no, name, percentage and stream) one record at a
time from the user till user wants. Each record is represented as a list object
Program - import pickle
file=open("stud.dat","wb")
while True:
rno = int(input("\nEnter roll no -"))
name = input("enter name- ")
perc = float(input("Enter Perc -"))
str = input("Enter stream -")
dets = [rno,name,perc,str] # data combined into the list object dets
pickle.dump(dets,file)
ans=input("Want to enter another (y/n) - ")
if ans in "nN":
break
file.close()
Data inputted of each student is combined into the list object dets and then written into the
Binary file record by record
Reading Binary File
The load() method is used to read (unpickle) data from a binary file. The file
to be read by load() method need to be opened in binary read (rb) mode.
Syntax : data _object = pickle.load(file_object)
● The load() method takes the file handle(file_object), used to open the
binary file in read mode as argument and reads the pickled object from
the file.
● The unpickled data returned by load() gets stored in the data_object.
● The object returned by load() can be a list/tuple/dictionary depending on
how the data is dumped.
● If the binary file was created using a list (tuple), then
pickle.load(file_object) will read a list (tuple) and store it in the list/tuple
object. If the binary file was created using a dictionary object to represent
each record, then pickle.load(file_object) will read each record and store
the data in a dictionary object.
Creation and reading Binary File
Example : Write a program to create a text file and read and display the details stored in
the Binary file stud.dat .
Output :
Program : import pickle
file = open("stud.dat","wb") Enter roll no -1
while True: enter name- aaa
rno = int(input("\nEnter roll no -")) Want to enter another (y/n) - y
name = input("enter name- ") Enter roll no -2
dets = [rno,name] enter name- bbb
pickle.dump(dets,file) Want to add another (y/n) - n
ans=input("Want to add another - ") [1, 'aaa']
if ans in ("n","N"): [2, 'bbb']
break EOFError: Ran out of input
file.close() The dump() when reaches eof() afer
fin=open("stud.dat","rb") reading stored records, results an
while True: exception. Hence to rectify it, the
studrecs = pickle.load(fin) reading of Binary file is given within an
print(studrecs) exception Handler
fin.close()
Handling Exception in Binary File Manipulation
An Exception is an error that happens during the execution of
a program. The try, except, else and finally block of Python is
used to catch and handle exceptions.
Syntax :
try:
includes the code that may cause exceptions
except <Exception>:
holds the code that handle exceptions
else:
includes code that executes when no exception occurs
finally:
code that executes whether exception occurs or not
A single try statement can have multiple except statements
and give when the try block contains statements that may
throw different types of exceptions . A generic except clause
without the exception name can be given to handles any
exception.
The else and finally block are optional and can be omitted.
Handling Exception in Binary File Manipulation
While reading a Binary file, the pickle.load() may cause the exception EOFError, when the file
pointer reaches the end-of-file. The try and except block is used to handle the exception.
In the try block, the code to read/manipulate the binary file is written and the except block
contains the code to be executed when the exception occur.
Program : To read and count no. of records present in Binary file student.dat
fin, ctr = open("student.dat","rb"),0
try:
while True:
studrecs = pickle.load(fin)
print(studrecs)
ctr += 1
except FileNotFoundError:
print("No such File“)
except EOFError:
fin.close()
else:
pass
finally:
print("no. of records =" ,ctr)
Binary File Manipulation
WAP to create the file item.dat and perform import pickle
the following operations on user’s given from os import remove, rename
choice. Each record of item.dat has item no,
name, price and quantity which is def createfile():
represented as a list object. file = open("item.dat","wb")
The menu options include ans = "y"
1. create Item details File while ans == "y":
2. show and count all records ino = int(input("\nitem no -"))
3. search on item no name = input(“\nName- ")
4. search on item name price = float(input(“\nPrice -"))
5 Display total values qty = int(input(“\nQuantity -"))
6. Edit on item no itdets = [ino,name,price,qty]
7. Edit on item name pickle.dump(itdets,file)
8. Insert at nth position ans = input("add more ?(y/n) - ")
9. Delete nth record file.close()
10 Delete on item no
Binary File Manipulation
def display_count(): def srchino():
totrec=0 sino = int(input("Enter item no -"))
try: try:
with open("item.dat","rb") as fin: with open("item.dat","rb") as fin:
while True: while True:
itrec = pickle.load(fin) itrec = pickle.load(fin)
print(itrec) if itrec[0] == sino:
totrec+=1 print("item name - ",itrec[1])
except EOFError: print("Price - ",itrec[2])
pass print("Stock - ",itrec[3])
print("No. of records in the file ",totrec) break
else:
print("Record not found")
except EOFError:
pass
Binary File Manipulation
def srchinm():
sinm = input("Enter item name -")
found = "n"
try: def sumitemvalues():
with open("item.dat","rb") as fin: totsum=0
while True: try:
itrec = pickle.load(fin) with open("item.dat","rb") as fin:
if itrec[1] == sinm: while True:
print("item no - ",itrec[0])
itrec = pickle.load(fin)
print("Price - ",itrec[2])
print("Stock - ",itrec[3]) totsum += itrec[2]*itrec[3]
found = "y" except EOFError:
pass
if found == "n": print("Total values of all items - ",totsum)
print("Record not found")
except EOFError:
pass
Binary File Manipulation
def editonino():
file = open("item.dat","rb")
sino, found, allrecs = int(input("Enter Item no to edit -")), "n", []
try:
while True:
itrec = pickle.load(file)
if itrec[0] == sino:
itrec[1] = input("Enter edited name -")
itrec[2] = float(input("Enter edited Price -"))
itrec[3]=int(input("Enter edited quantity in stock -"))
found="y"
allrecs+=[itrec] # Records added the records to a nested list
except EOFError:
if found == "n":
print("No such record")
else:
file.close()
file = open("item.dat","wb")
for rec in allrecs:
pickle.dump(rec,file) #Records written into item.dat
file.close()
Binary File Manipulation
def editonrec():
file = open("item.dat","rb")
n, found, allrecs = int(input("Enter rec no to edit -")), "n“, []
try:
while True:
itrec = pickle.load(file)
rec += 1
if rec == n:
itrec[1], itrec[2] = input("Enter edited name -"), float(input("Enter edited Price -"))
itrec[3]=int(input("Enter edited quantity in stock -"))
found="y"
allrecs += [itrec] #Records added the records to a nested list
except EOFError:
if found == "n":
print("No such record")
else:
file.close()
file = open("item.dat","wb")
for rec in allrecs:
pickle.dump(rec,file) #Records written into item.dat

file.close()
Binary File Manipulation
def editoninm():
file = open("item.dat","rb")
snm = input("Enter item name to edit -")
found, allrecs = "n",[]
try:
while True:
itrec = pickle.load(file)
if itrec[1] == snm:
itrec[1] = input("Enter edited name -")
itrec[2] = float(input("Enter edited Price -"))
itrec[3]=int(input("Enter edited quantity in stock -"))
found = "y"
allrecs + =[itrec] #Records added the records to a nested list
except EOFError:
if found == "n":
print("No such record")
else:
file.close()
file = open("item.dat","wb") #item.dat opened in wb mode
for rec in allrecs:
pickle.dump(rec,file) #Records written into item.dat
file.close()
def insnth():
Binary File Manipulation
file = open("item.dat","rb")
n, found,rec, allrecs = int(input("Enter rec no -")), "n", 0, []
try:
while True:
itrec = pickle.load(file)
rec += 1
if rec == n:
ino, name = int(input("\nEnter item no -")), input("enter name- ")
price,qty = float(input("Enter Price -")), int(input("Enter Stock Quantity -"))
nrec = [ino,name,price,qty]
allrecs += [nrec] #new record added in nested list
found="y"
allrecs+=[itrec] #Existing record added in nested list
except EOFError:
if found == "n":
print("No such record")
else:
file.close()
file = open("item.dat","wb")
for rec in allrecs: #record(list object) from nested list assigned to rec
pickle.dump(rec,file) #records from nested list written into the file
file.close()
Binary File Manipulation
def insertitno(): #insertion before item no
file = open("item.dat","rb")
ino,found, allrecs = int(input("Enter item no -")),"n“,[]
try:
while True:
itrec = pickle.load(file)
allrecs += [itrec] #Existing record added in nested list
if itrec[0] == ino:
ino , name = int(input("\nEnter item no -"),input("enter name- ")
price, qty = float(input("Enter Price -")),int(input("Enter Stock Quantity -"))
nrec = [ino,name,price,qty]
allrecs += [nrec] #new record added in nested list
found="y"
except EOFError:
if found == "n":
print("No such record")
else:
file.close()
file = open("item.dat","wb")
for rec in allrecs: #record(list object) from nested list assigned to rec
pickle.dump(rec,file) #records from nested list written into the file
file.close()
def delnth(): Binary File Manipulation
file = open("item.dat","rb")
rno, currec,found = int(input("Enter record no to delete -")),0,"n"
allrecs = []
try:
while True:
itrec = pickle.load(file)
currec += 1
if currec == rno:
found = "y"
else:
allrecs += [itrec] #record not equal to rno added to nested list
except EOFError:
file.close()
if found == "n":
print("No such record")
else:
file = open("item.dat","wb")
for rec in allrecs: #record(list object) from nested list assigned to rec
pickle.dump(rec,file) ) #records from nested list written into the file
file.close()
Binary File Manipulation
def delitno():
file = open("item.dat","rb")
ino ,found ,allrecs = int(input("Enter item no to delete -")),"n“,[]
try:
while True:
itrec = pickle.load(file)
if itrec[0] == ino:
found = "y"
else:
allrecs += [itrec] #record not equal to ino added to nested list
except EOFError:
file.close()
if found == "n":
print("No such record")
else:
file = open("item.dat","wb")
for rec in allrecs:
pickle.dump(rec,file)
file.close()
Binary File Manipulation
while True:
print("\n1. create Item details File\n2. show and count all\ records\n3. search on item no\n4.
search on item name\n5. Display total values\n6.Edit on item no\n7. Edit on Item name\n8.
Insert at nth position\n8. Insert after item no\n110.Delete nth\ record\n11. Delete an item
no\n") elif ch==7:
ch = int(input("Enter your choice- ")) editoninm()
if ch==1: elif ch==8:
createfile() insertatnth()
elif ch==2: elif ch==9:
display_count() insertitno()
elif ch==3: elif ch==10:
srchino() delnth()
elif ch==4: elif ch==11:
srchinm() delitno()
elif ch==5: else:
sumitemvalues() print("wrong choice")
elif ch==6: ans=input("\n want to continue(y/n)")
editonino() if ans in "nN"):
break
Binary File Manipulation (nested List)
Example :
Write a menu driven program to create the file stud.dat and perform the following
operations on user’s given choice. Each record of stud.dat has rollno, name, %age and
stream which is represented as an element of nested list
1. create student File
2. Display all student records
3. count total records stored in the file
4. count student records for perc >= given perc
5. search on roll no
6. search on name
7. count record of a user given stream
8. Edit record matching a user given roll no
9. Edit record matching a user given record no
10. Insert record at a given record no
11. Insert record after a given roll no
12. Delete nth record
13. Delete record matching a roll no
Binary File Manipulation (nested List)
import pickle def display():
def create(): fin = open("stud.dat","rb")
fobj = open("stud.dat","wb") ctr = 0
studrecs = pickle.load(fin)
studdets=[]
for r in studrecs:
while True: print(r)
rno = int(input("\nEnter roll no -")) print("\n***contents of stud.dat****")
name = input("enter name- ") fin.close()
perc = float(input("Enter Perc -"))
str = input("Enter stream -") def countall():
studdets += [[rno,name,perc,str]] fin = open("stud.dat","rb")
ans = input("Want to add more") ctr = 0
if ans in ("n","N"): studrecs = pickle.load(fin)
break for r in studrecs:
pickle.dump(studdets,fobj) ctr += 1
fobj.close() fin.close()
print("No of Records",ctr)
Binary File Manipulation (nested List)
def dispcountperc():
fin = open("stud.dat","rb")
ctr=0
sperc = float(input("Enter %age - "))
def countstream():
studrecs = pickle.load(fin) fin = open("stud.dat","rb")
for r in studrecs: strctr=0
if r[2] >= sperc: strnm = input("Enter stream name - ")
print("Roll no- ",r[0]) studrecs = pickle.load(fin)
print("Name - ",r[1]) for r in studrecs:
print("Percentage - ",r[2]) if r[3] == strnm:
print("Stream - ",r[3]) strctr+=1
ctr+=1 fin.close()
fin.close() print("No of students in ",strnm,"stream\
print("\nNo of students scoring %age\ =",strctr)
>= ",sperc,"% = ",ctr)
Binary File Manipulation (nested List)
def searchrno(): def searchname():
fin = open("stud.dat","rb") fin = open("stud.dat","rb")
srno = int(input("Enter roll no - ")) found="n"
studrecs = pickle.load(fin) srnm = input("Enter name to search - ")
for r in studrecs: studrecs = pickle.load(fin)
if r[0] == srno: for r in studrecs:
print("Name - ",r[1]) if r[1] == srnm:
print("Percentage - ",r[2]) print("Roll no- ",r[0])
print("Stream - ",r[3]) print("Percentage - ",r[2])
break print("Stream - ",r[3])
else: found="y"
print("no such record") fin.close()
fin.close() if found=="n":
print("No such record")
Binary File Manipulation (nested List)
def updaterecno(): def updaterno():
fin = open("stud.dat","rb+") fin = open("stud.dat","rb+")
rno = int(input("Enter rec no to edit - ")) srno = int(input("Enter roll no to edit - "))
ctr=0 studrecs = pickle.load(fin)
srecs = pickle.load(fin) for r in srecs:
if recno <= len(srecs): if r[0] == srno:
r[1] = input("Enter name -")
print(“Enter updated data“)
r[2] = float(input("Enter %age-"))
srecs[rno][1] = input("Enter name -")
r[3] = input("Enter stream -")
srecs[rno][2] = float(input("%age-")) found="y"
srecs[rno][3] = input("stream -") break
fin.seek(0) if found == “y”;
pickle.dump(studrecs,fin) fin.seek(0)
print("data updated in file") pickle.dump(studrecs,fin)
fin.close() else:
else: print(“No such student record in file")
print(“invalid record no“) fin.close()
Binary File Manipulation (nested List)
#alternative code for editing a record = given roll no #alternative code for editing a given record no
def updaterno(): def updaterecno():
fin = open("stud.dat","rb") fin = open("stud.dat","rb")
srno = int(input("Enter rno to edit - ")) rno = int(input("Enter rec no to edit - "))
srecs = pickle.load(fin) ctr = 0
found = "n" srecs = pickle.load(fin)
for r in srecs: if recno <= len(studrecs):
if r[0] == srno: print(“Enter edited data“)
r[1] = input("Enter name -") srecs[rno][1] = input("Enter name -")
r[2] = float(input("Enter %age-")) srecs[rno][2] = float(input("%age-"))
r[3] = input("Enter stream -") srecs[rno][3] = input("stream -")
fin.close() fin.close()
fin = open("stud.dat",“wb") fin = open("stud.dat",“wb")
pickle.dump(studrecs,fin) pickle.dump(studrecs,fin)
break print("data updated in file")
else: else:
print("No such student record in file") print(“invalid reco no“)
fin.close() fin.close()
Binary File Manipulation (nested List)
def insertrno(): #Alternative Logic
def insertrno():
fin = open("stud.dat","rb")
fin = open("stud.dat","rb+")
srno,ctr,found = int(input(Enter roll no -)),0,”n”
srno, ctr, found = int(input(Enter roll no -)),0,”n”
studrecs = pickle.load(fin)
studrecs = pickle.load(fin)
for r in studrecs:
for r in studrecs:
ctr +=1
ctr +=1
if r[0] == srno:
if r[0] == srno:
rno=int(input("\nEnter rollno -"))
rno = int(input("\nEnter rollno -"))
name = input("enter name- ")
name = input("enter name- ")
perc = float(input("Enter Perc -"))
perc = float(input("Enter Perc -"))
strm = input("Enter stream -")
strm = input("Enter stream -")
newdets=[rno,name,perc,strm]
newdets = [rno,name,perc,strm]
studrecs.insert(ctr-1,newdets)
studrecs.insert(ctr-1,newdets)
fin.close()
fin.seek(0)
fin = open("stud.dat",“wb")
pickle.dump(studrecs,fin)
pickle.dump(studrecs,fin)
break
break
else:
else:
print("rec not found")
print(“rec not found”)
fin.close()
fin.close()
Binary File Manipulation (nested List)
def insertnth(): def insertnth(): #Alternative Logic
pos = int(input(Enter record no to add)) fin = open("stud.dat","rb")
fin = open("stud.dat","rb+") pos = int(input("Enter rec no to insert"))
studrecs = pickle.load(fin) studrecs = pickle.load(fin)
if pos <= len(studerecs): if pos <= len(studrecs):
print("Enter the new Record ") rno=int(input("\nEnter roll no -"))
rno = int(input("\nEnter roll no -"))
name=input("enter name- ")
name = input("enter name- ")
perc=float(input("Enter Perc -"))
perc = float(input("Enter Perc -"))
strm = input("Enter stream -") strm =input("Enter stream -")
newdets = [rno,name,perc,strm] newdets=[rno,name,perc,str]
studrecs.insert(pos-1,newdets) studrecs.insert(pos – 1, newdets)
fin.seek(0) fin.close()
pickle.dump(studrecs,fin) fin = open("stud.dat",“wb")
else: pickle.dump(nestlst,fin)
else:
print(“Invalid Record no“) print(“Invalid Record Position“)
fin.close() fin.close()
Binary File Manipulation (nested List)
def deleteroll(): def deletenm():
nstlst=[] nstlst = []
fin = open("stud.dat","rb+") fin = open("stud.dat","rb+")
found='n' found='n'
rno = int(input("Enter rollno to delete - ")) nm = int(input("Enter Name to delete - "))
studrecs = pickle.load(fin) studrecs = pickle.load(fin)
for r in studrecs: for r in studrecs:
if r[0] == rno: if r[1] == nm:
found = "y" found = "y"
else: else:
nstlst+=[r] nstlst += [r]
if found=="n": if found == "n":
print("no such record") print("no such record")
else: else:
fin.seek(0) fin.seek(0)
pickle.dump(nstlst,fin) pickle.dump(nstlst,fin)
fin.close() fin.close()
Binary File Manipulation (nested List)
def deletenth():
nstlst=[]
cnt = 0
fin = open("stud.dat","rb+")
def deletenth(): #Alternative Logic
found='n' fin = open("stud.dat","rb+")
pos = int(input("Record no to delete - ")) found='n'
studrecs = pickle.load(fin) pos = int(input("Record no to delete - "))
if pos <= len(studrecs): studrecs = pickle.load(fin)
for r in studrecs: if pos <= len(studrecs):
if cnt == pos:
studerecs.pop(pos-1)
found="y"
else:
fin.seek(0)
nstlst += [r] pickle.dump(nstlst,fin)
cnt+=1 fin.close()
fin.seek(0)
pickle.dump(nstlst,fin)
else:
print(“invalid Record no“)
fin.close()
Binary File Manipulation (nested List)
while True:
ch = int(input("\n1. create student File\n2. show all records\\n3. Count records\n 4.\ Display &\
count for perc >=given perc\n5. Search on roll no\n6. search on name\n7.\ count on stream\n8.
Edit on roll no\n 9. Edit on rec no\n10. Insert nth record\n11. Insert after user given\ rolno\n
12.delete nth record\n13.Delete on name\nEnter your choice- "))
if ch == 1: elif ch == 9:
create() updaterecno()
elif ch == 2: elif ch == 10:
display() insertnth()
elif ch == 3: elif ch == 11:
countall() insertroll()
elif ch == 4: elif ch == 12:
dispcountperc() deletenth()
elif ch == 5: elif ch ==13:
searchrno() deleteroll()
elif ch == 6: elif ch == 14:
searchname() deletenm()
elif ch == 7: else:
countstream() print("wrong choice")
elif ch == 8: ans = input("\n want to continue with (y/n)")
updaterno() if ans in("n","N"):
break
Binary File Manipulation (Dictionary)
Write a menu driven program to create the file item.dat and perform the following
operations on user’s given choice. Each record of item.dat has item no as key and the value
part item name, price is represented as list.
1. Create file
2. Display Records
3. Count all records
4. Search On item no
5. Search On item name
6. Count all records for price >= user given price
7. Edit on user given record no
8. Edit on user given item no
9. Insert at user given record no
10. Insert after user given item no
11. Delete a user given item no
12. Delete a user record no
Binary File Manipulation (Dictionary)
import pickle def show():
def create(): f1 = open("item.dat","rb")
f1 = open("item.dat","wb")
rec = {} rec = pickle.load(f1)
while True: f1.close()
ino = int(input("Enter item no ")) for kino in rec:
name = input("Enter Item Name ") print(kino,rec[kino])
price = float(input("Enter price "))
rec[ino] = [name,price]
ans = input("Continue(y/n)") def countrec():
if ans in "Nn": f1 = open("item.dat","rb")
break rec = pickle.load(f1)
pickle.dump(rec,f1) f1.close()
f1.close()
print("Total no of records",len(rec))
Binary File Manipulation (Dictionary)

def countprice():
spr = float(input("Enter price to compare - "))
f1 = open("item.dat","rb") def srchino():
ctr = 0 kino = int(input("item no to search - "))
rec = pickle.load(f1) f1 = open("item.dat","rb")
f1.close() rec = pickle.load(f1)
for kino in rec: f1.close()
if rec[kino][1] >= spr: if kino in rec:
ctr += 1 print(kino,rec[kino])
if ctr == 0: else:
print("No such record") print("No such record")
else:
print("No. of items with price >=",spr,"
Binary File Manipulation (Dictionary)
def srchino(): def srchinm():
kino = int(input("item no to search - ")) kinm = input("Item name to search - ")
f1 = open("item.dat","rb") f1 = open("item.dat","rb")
rec = pickle.load(f1) ctr = 0
f1.close() rec = pickle.load(f1)
if kino in rec: for kino in rec:
print(kino,rec[kino]) if rec[kino][0] == kinm:
else: print(kino,rec[kino])
print("No such record") ctr += 1
if ctr == 0:
print("No such record")
f1.close()
Binary File Manipulation (Dictionary)

def editrecno(): def edititemno():


n = int(input("Enter rec no")) sino = int(input("Enter item no"))
f1 = open("item.dat","rb+") f1 = open("item.dat","rb+")
ctr = 0 found=0
rec = pickle.load(f1) rec = pickle.load(f1)
for k in rec: if sino in rec:
rec[sino][0]=input("Enter name")
ctr += 1
rec[sino][1]=float(input("Enter price"))
if ctr == n:
found=1
rec[k][0] = input("Enter name") if found==1:
rec[k][1] = float(input("Enter price")) f1.seek(0)
break pickle.dump(rec,f1)
f1.seek(0) else :
pickle.dump(rec,f1) print("record not found")
f1.close()
Binary File Manipulation (Dictionary)
def insertrecno(): def insertino():
n = int(input("Enter rec no")) sino = int(input("Enter item no - "))
f1= open("item.dat","rb") f1= open("item.dat","rb")
ctr = 0 rec = pickle.load(f1)
rec = pickle.load(f1)
f1.close()
f1.close()
found, newrec = 0, {}
if len(rec) < n:
prnt("invalid record no")
for k in rec:
return newrec[k] = rec[k]
newrec = {} if k == sino:
for k in rec: ino = int(input("Enter itemno - "))
ctr+=1 name = input("Enter Name - ")
if ctr == n: pr = float(input("Enter Price - "))
ino = int(input("item no ")) newrec[ino] = [name,pr]
name = input("item Name ") found = 1
pr = float(input(“ Price ")) if found == 1:
newrec[ino] = [name,pr] f1 = open("item.dat","wb")
newrec[k] = rec[k] pickle.dump(newrec,f1)
f1 = open("item.dat","wb")
f1.close()
pickle.dump(newrec,f1)
else:
f1.close()
print("No such record found")
Binary File Manipulation (Dictionary)
def delrno():
def delino(): srno = int(input("Enter recno to delete"))
sino = int(input("item no to delete")) f1 = open("item.dat","rb")
f1 = open("item.dat","rb") found = ctr = 0
rec = pickle.load(f1)
found = 0
f1.close()
rec = pickle.load(f1)
for k in rec:
f1.close()
ctr += 1
if sino in rec:
if ctr == srno:
rec.pop(sino)
rec.pop(k)
found = 1 found = 1
if found == 1: break
f1 = open("item.dat","wb") if found == 1:
pickle.dump(rec,f1) f1 = open("item.dat","wb")
f1.close() pickle.dump(rec,f1)
else: f1.close()
print("No such record found") else:
print("No such record found")
Binary File Manipulation (Dictionary)
while True:
CH = int(input("\n1. Create\n 2. Display records\n 3. Count all records \n 4. Search On\
item no\n 5. Search On item name\n 6. Count all records for price >= equal to user given\
price\n 7. Edit on user given record no\n 8. Edit on user given itemno\n9.Insert at user\
given record no\n10. Insert after user given item no\n 11.Delete a user given item no\n\
12. Delete a user record no\nEnter your\Choice(1-12)"))
if CH == 1: elif CH == 9:
create() insertrecno()
elif CH ==2: elif CH == 10:
show() insertino()
elif CH == 3: elif CH == 11:
countrec() delino()
elif CH == 4: elif CH == 12:
srchino() delrno()
elif CH == 5: else:
srchinm() print("Incorrect choice")
elif CH == 6: ans = input("want to continue Yy Nn")
countprice() if ans in "Nn":
elif CH == 7: break
editrecno()
Binary File Manipulation (Dictionary)
Example :
Write a menu driven program to create the file emp.dat and perform the following
operations on user’s given choice. Each record of emp.dat has emp no, name,
salary and department as fields. The data part is represented as a dictionary
object.
1. Create file
2. Display Records
3. Search On Emp no
4. Search On Emp name
5. Count records of Department
6. Modify On Emp no
7. Display Highest salary
8. Quit Program
Binary File Manipulation (Dictionary)
import pickle
from os import remove, rename
def Create():
with open("emp.dat","wb") as File:
while True:
Eno = int(input("Eno :" ))
Name = input("Name :")
Sal = float(input("Salary:"))
Dept = input("Department :")
Emp= {"Eno":Eno,"Name":Name,"Sal":Sal,"Dept":Dept}
pickle.dump(Emp,File)
Ans=input("More Y/N ?")
if Ans in 'nN':
break
Binary File Manipulation (Dictionary)
def Disp():
try:
with open("emp.dat","rb") as File:
while True:
Emp = pickle.load(File)
print(Emp)
except EOFError:
pass
def Countall():
ctr=0
try:
with open("emp.dat","rb") as File:
while True:
Emp = pickle.load(File)
ctr+=1
except EOFError:
print(“Total no. of records in file - " ,ctr)
Binary File Manipulation (Dictionary)
def searcheno():
found=0
Seno = int(input("Enter Employee no to search - "))
try:
with open("emp.dat","rb") as File:
while True:
Emp = pickle.load(File)
if Emp["Eno"] == Seno:
print(Emp)
found=1
break
except EOFError:
if found==0:
print("No such Record Found")
Binary File Manipulation (Dictionary)
def searchenm():
Senm = input("Enter Employee name to search - ")
found = "n"
try:
with open("emp.dat","rb") as File:
while True:
Emp = pickle.load(File)
if Emp["Name"]== Senm:
print(Emp)
found="y"
except EOFError:
pass
if found=="n":
print("No such Record Found")
Binary File Manipulation (Dictionary)
def CountDept():
ctr=0
Sdept = input("Enter Department -")
try:
with open("emp.dat","rb") as File:
while True:
Emp = pickle.load(File)
if Emp["Dept"] == Sdept:
print(Emp)
ctr+=1
except EOFError:
print("No. of Employees in", Sdept," - ",ctr)
Binary File Manipulation (Dictionary)
def Countsal():
ctr=0
Ssal = float(input("Enter Department -"))
try:
with open("emp.dat","rb") as File:
while True:
Emp = pickle.load(File)
if Emp[“Sal"] >= Ssal:
print(Emp)
ctr+=1
except EOFError:
print("No. of Employees whose salary is >=", Ssal ," - ",ctr)
Binary File Manipulation (Dictionary)
def highestsal():
file = open("emp.dat","rb")
Emprec = pickle.load(file) #first record read
hsal = Emprec["Sal"]
try: # To check eof
while True:
Emprec = pickle.load(file)
if Emprec["Sal"] > hsal:
hsal = Emprec["Sal"]
except EOFError:
file.close()
print("Highest Salary -",hsal)
Binary File Manipulation (Dictionary)
def EditOnEmpno():
file = open("emp.dat","rb")
Seno ,ndict ,found = int(input("Enter Employee no to Edit - ")),[], "n"
try:
while True:
Emp = pickle.load(file)
if Emp["Eno"] == Seno:
eno = Emp["Eno"]
Nm ,Sal , D = input(" Name :"),float(input("Salary:")), input("Dept :")
Empnew={"Eno":eno,"Name":Nm,"Sal":Sal,"Dept":D}
found = "y"
ndict+=[Empnew] #List of dictionary
else:
ndict+= [Emp]
except EOFError:
file.close()
if found=="n":
print("Record not found")
else:
file = open("emp.dat","wb")
for r in ndict:
pickle.dump(r,file)
file.close()
Binary File Manipulation (Dictionary)
def EditOnrecno():
file = open("emp.dat","rb")
Srec, found, ctr,ndict = int(input("Enter Record no to Edit - ")),"n",0,[]
try:
while True:
Emp = pickle.load(file)
ctr +=1
if ctr == Srec:
eno = Emp["Eno"]
Nm ,Sal ,D = input(" Name :"),float(input("Salary:")), input("Dept :")
Empnew = {"Eno":eno,"Name":Nm,"Sal":Sal,"Dept":D}
ndict+=[Empnew] #List of dictionary
found = “y"
else:
ndict+= [Emp]
except EOFError:
file.close()
if found=="n":
print("Record not found")
else:
file = open("emp.dat","wb")
for r in ndict:
pickle.dump(r,file)
file.close()
Binary File Manipulation (Dictionary)
while True:
CH = input("1. Create\n2. Display\n3. Search On Emp no\n4.\ Search On Emp name\n 5. Count\
all records\n6. Count records of a given Department\n7. Count records > = given salary 8. Modify\
On Emp no\n 9. Modify a record no 10. Display Highest\ salary\n 8.Quit\n\ Enter your Choice(1-8)")

if CH=='1': elif CH==‘7':


Create() Countsal()
elif CH=='2': elif CH==‘8':
Disp() EditOnEmpno()
elif CH=='3': elif CH=='9':
searcheno() EditOnrecno()
elif CH=='4': elif CH==‘10':
searchenm() highestsal()
elif CH=='5': else:
Countall() break
elif CH==‘6':
CountDept()
Assessment
Which of the following statement(s) are correct regarding the file access modes?
a. ‘rb+’ opens a file for both reading and writing. File object points to its
beginning.
b. ‘wb+’ opens a file for both writing and reading. Adds at the end of the
existing file if it exists and creates a new one if it does not exist.
c. ‘wb’ opens a file for reading and writing in binary format. Overwrites the
file if it exists and creates a new one if it does not exist.
d. ‘ab’ opens a file for appending. The file pointer is at the start of the file if
the file exists.
Answer : a
Which of the following commands is used to write the list L into the binary file,
student.dat which is opened using file handle F?
a. pickle.write(L,f)
b. pickle.write(f, L)
c. pickle.dump(L,F)
d. f=pickle.dump(L)
Answer : c. pickle.dump(L,F)
Assessment
Which of the following statement is incorrect in the context of binary files?
a. Information is stored in the same format in which the information is held in
memory.
b. No character translation takes place
c. Every line ends with a new line character
d. pickle module is used for reading and writing
Answer : c

Trying to open a binary file using a text editor will show:


a. Garbage values b. ASCII values c. Binary character d. Unicodes
Answer : a. Garbage Values.

A file maintains a __________ which tells the current position in the file where writing or
reading will take place.
a. line b. file pointer c. list d. order
Answer : b. file pointer
Assessment
Which of the following file modes opens a file for appending and reading in a
binary file and moves the files pointer at the end of the file if the file already
exists or creates a new file?
a. a b. a+ c. ab+ d. ab
Answer: c. ab+

Which method of pickle module is used to write onto a binary file?


a. dump()
b. load()
c. write()
d. None of the above
Answer : a. dump()
Assessment
Correct statement to import pickle module in our program is :
a. Import Pickle
b. import pickle
c. import pickle module
d. pickle.import
Answer : b. import pickle

To open a binary file named info.dat for adding more records, which of the
following statements is correct?
a. f1 = open (“info.dat” , ‘ab’)
b. f1 = open (“info.dat” , ‘wb’)
c. f1 = open (“info.dat”)
d. f1 = open (“info.dat”,”wb+”)
Answer : a. f1 = open (“info.dat” , ‘ab’)
Assessment
Which of the following option is not correct for Binary file?
a. if we try to read a Binary file that does not exist, an error occurs.
b. if we try to read a Binary file that does not exist, the file gets created.
c. if we try to write on a Binary file that does not exist, no error occurs.
d. if we try to write on a Binary file that does not exist, the file gets
Created.
Answer : b.

Which of the following statement is true?


a. pickling creates an object from a sequence of bytes
b. pickling is used for object serialization
c. pickling is used for object deserialization
d. pickling is used to manage all types of files in Python
Answer : b.
Assessment
Raghav is trying to write a tuple tup1 = (1,2,3,4,5) on a binary file test.bin.
Consider the following code written by him.
import pickle
tup1 = (1,2,3,4,5)
myfile = open("test.bin",'wb')
pickle._______ #Statement 1
myfile.close()
Identify the missing code in Statement 1.
a. dump(myfile,tup1)
b. dump(tup1, myfile)
c. write(tup1,myfile)
d. load(myfile,tup1)
Answer : b. dump(tup1, myfile)
Assessment
A binary file employee.dat has following data
Empno empname Salary
101 Anuj 50000
102 Arijita 40000
103 Hanika 30000
104 Firoz 60000
105 Vijaylakshmi 40000
def display(eno):
f = open("employee.dat","rb")
totSum = 0 Choose the correct option
try: a. jump
while True: b. break
R=pickle.load(f) c. continue
if R[0]==eno:
d. return
__________ #Line1
totSum=totSum+R[2] Answer : c. continue
except:
f.close()
print(totSum)
When the above mentioned function, display (103) is executed, the output displayed is 190000.
Write appropriate jump statement from the following to obtain the above output.
Assessment
Which of the following statement opens a binary file record.bin in write mode
and writes data from a list lst1 = [1,2,3,4] on the binary file?
a. with open('record.bin','wb') as myfile:
pickle.dump(lst1,myfile)
b. with open('record.bin','wb') as myfile:
pickle.dump(myfile,lst1)
c. with open('record.bin','wb+') as myfile:
pickle.dump(myfile,lst1)
d. with open('record.bin','ab') as myfile:
pickle.dump(myfile,lst1)

Answer : a. with open('record.bin','wb') as myfile:


pickle.dump(lst1,myfile)

You might also like