Binary File Handling
Binary File Handling
Binary File Handling
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.
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)
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+
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.