Python-Binary Files - Notes
Python-Binary Files - Notes
Python pickle
Pickle is used for serializing and de-serializing Python object. Serialization refers to the process of
converting an object in memory to a byte stream that can be stored on disk (backing storage). Later on,
this byte stream can then be retrieved and de-serialized back to a Python object (variable). In Python
process of serialization and de-serialization is called is pickling. For pickling in Python has pickle module.
Variable fobj is a binary data file object created with open(). File mode contains 2-characters string.
Letter 'a' for append mode and letter 'b' for binary. If a binary file is to be opened in write mode,
then letter 'w' will replace letter 'a'. Data to be written into the binary is a list emp. Statement
pickle.dump(emp, fobj) writes a record into a binary file data file. One record is written at a time
in the binary data file. A binary file can store dictionary type data also. Function is given below showing
how to store dictionary data in a binary data file:
import pickle
def addrec():
fobj=open('SALARY.DAT', 'ab')
for k in range(5):
code:int(input('Code? '))
name:input('Name? ')
bsal:float(input('BSal? '))
emp={'code':code, 'name':name.upper(), 'bsal':bsal}
pickle.dump(emp, fobj)
fobj.close()
Variable emp is a dictionary.
Page 1/9
Python Notes Class XII Binary File
Python function to display a binary data file containing list type of data is given below:
import pickle
def showrec():
fobj=open('SALARY.DAT', 'rb')
try: Variable emp is either a list or a tuple.
while True:
emp=pickle.load(fobj)
print(emp[0],emp[1],emp[2],sep='\t')
except:
fobj.close()
Variable fobj is a binary data file object created with open(). File mode contains 2-characters string.
Letter for 'r' read mode and letter 'b' for binary. Statement emp=pickle.load(fobj) reads a
record from the binary file stores data in a list type variable emp. An infinite while-loop is used to read
every record from the binary data file and then display the record because it will be impossible to
remember number of dump() operations. Reading beyond the end of the file, will trigger a run-time
error (exception), pickle.load() fails to read data from the binary data file. When an exception is
triggered in the try part, the program control jumps to except part. In the except part, file will be
closed. As discussed earlier, a binary data can contain dictionary type data. Function is given below to
display a binary data file containing dictionary type of data:
import pickle
def showrec():
fobj=open('SALARY.DAT', 'rb') Variable emp is a dictionary.
try:
while True:
emp=pickle.load(fobj)
print(emp['code'],emp['name'],emp['bsal'],sep='\t')
except:
fobj.close()
Kindly note: number of load() must match number dump() when reading from a binary data file.
Since it impossible to remember the count, try-except is used to read from a binary file without
triggering any run-time (exception) error. Data in a binary data file can be stored either as a list type or
a dictionary type or any other type, but hence forth, all the functions will assume that the data is stored
as a list in the binary data file.
Function to search for code in a binary data file (containing list type of data) is given below:
import pickle
def searchcode():
code=int(input('Code to Search? '))
fobj=open('SALARY.DAT', 'rb')
found=0
try:
while True:
emp=pickle.load(fobj)
if code==emp[0]:
print(emp[0],emp[1],emp[2],sep='\t')
found=1
break
except:
fobj.close()
if found==0:
print(code, 'not found in the file')
Page 2/9
Python Notes Class XII Binary File
Function to search for name in a binary data file (containing list type of data) is given below:
import pickle
def searchname():
name=input('Name to Search? ')
fobj=open('SALARY.DAT', 'rb')
found=0
try:
while True:
emp=pickle.load(fobj)
if name.upper()==emp[1]:
print(emp[0],emp[1],emp[2],sep='\t')
found=1
break
except:
fobj.close()
if found==0:
print(name, 'not found in the file')
Function to search for salary in a binary data file (containing list type of data) is given below:
import pickle
def searchbsal():
fobj=open('SALARY.DAT', 'rb')
c=0
try:
while True:
emp=pickle.load(fobj)
if emp[2]>150000.0:
print(emp[0],emp[1],emp[2],sep='\t')
c+=1
except:
fobj.close()
print('Number of Records=',c)
OR,
def searchbsal():
fobj=open('SALARY.DAT', 'rb')
c=0
try:
while True:
emp=pickle.load(fobj)
if emp[2]>150000.0:
print(emp[0],emp[1],emp[2],sep='\t')
c+=1
except:
fobj.close()
if c==0:
print('No Records Found in the File')
Function to edit all the records in a binary data file (containing list type of data) is given below:
import pickle
from os import remove, rename
def editallrecs():
frobj=open('SALARY.DAT', 'rb')
fwobj=open('TEMP.DAT', 'wb')
try:
Page 3/9
Python Notes Class XII Binary File
while True:
emp=pickle.load(frobj)
emp[2]+=10000 Every employee's bsal is increased by 10000.
pickle.dump(emp, fwobj)
except:
frobj.close()
fwobj.close()
remove('SALARY.DAT')
rename('TEMP.DAT','SALARY.DAT')
Function to edit a particular record (by inputting employee code) in a binary data file (containing list
type of data) is given below:
import pickle
from os import remove, rename
def editcode():
frobj=open('SALARY.DAT', 'rb')
fwobj=open('TEMP.DAT', 'wb')
code=int(input('Code to Edit? '))
found=0
try:
while True:
emp=pickle.load(frobj)
if code==emp[0]: Particular employee's bsal is increased by 10000.
emp[2]+=10000
found=1
pickle.dump(emp, fwobj)
except:
frobj.close()
fwobj.close()
remove('SALARY.DAT')
rename('TEMP.DAT','SALARY.DAT')
if found==1:
print('Record Updated in the File')
else:
print(code, 'No Records Found in the File')
Function to delete a record from a binary data file (containing list type of data) is given below:
import pickle
from os import remove, rename
def deletecode():
frobj=open('SALARY.DAT', 'rb')
fwobj=open('TEMP.DAT', 'wb')
code=int(input('Code to Edit? '))
found=0
try:
while True:
emp=pickle.load(frobj)
if code==emp[0]:
found=1
else:
pickle.dump(emp, fwobj)
except:
frobj.close()
fwobj.close()
Page 4/9
Python Notes Class XII Binary File
remove('SALARY.DAT')
rename('TEMP.DAT','SALARY.DAT')
if found==1:
print('Record Deleted From the File')
else:
print(code, 'No Records Found in the File')
import pickle
from os import remove, rename
def addrecords():
n=int(input('Number of Records? '))
fobj=open('EMPDATA.DAT', 'ab')
for k in range(n):
code=int(input('Code? '))
name=input('Name? ')
bsal=float(input('BSal? '))
emp=[code, name.upper(), bsal, 0.2*bsal]
pickle.dump(emp, fobj)
fobj.close()
def showrecords():
fobj=open('EMPDATA.DAT', 'rb')
try:
while True:
emp=pickle.load(fobj)
print(emp[0],emp[1],emp[2],emp[3],sep='\t')
except:
fobj.close()
def findrecord():
while True:
print('-- Search Menu --')
print('1. Search by Code')
print('2. Search by Name')
print('3. Search by Basic Greater')
print('4. Search by Basic in Range')
print('5. Search by Basic Lesser')
print('0. To Return')
cho=input('Choice[0-5]? ')
found=0
if cho=='1':
fobj=open('EMPDATA.DAT', 'rb')
code=int(input('Code to search? '))
try:
while True:
emp=pickle.load(fobj)
if code==emp[0]:
print('Employee details')
print('Code =', emp[0])
print('Name =', emp[1])
print('BSal =', emp[2])
print('HRA =', emp[3])
found=1
break
Page 5/9
Python Notes Class XII Binary File
except:
fobj.close()
if found==0:
print('Code =',code,'Not found in the file!')
elif cho=='2':
fobj=open('EMPDATA.DAT', 'rb')
name=input('Name to search? ')
try:
while True:
emp=pickle.load(fobj)
if name.upper()==emp[1]:
print('Employee details')
print('Code =', emp[0])
print('Name =', emp[1])
print('BSal =', emp[2])
print('HRA =', emp[3])
found=1
break
elif cho=='3':
fobj=open('EMPDATA.DAT', 'rb')
try:
while True:
emp=pickle.load(fobj)
if emp[2]>150000:
print(emp[0],emp[1],emp[2],emp[3],sep='\t')
found=1
except:
fobj.close()
if found==0:
print('No Records Found in the File!')
elif cho=='4':
fobj=open('EMPDATA.DAT', 'rb')
try:
while True:
emp=pickle.load(fobj)
if emp[2]>=125000 and emp[2]<=175000:
print(emp[0],emp[1],emp[2],emp[3],sep='\t')
found=1
except:
fobj.close()
if found==0:
print('No Records Found in the File!')
elif cho=='5':
fobj=open('EMPDATA.DAT', 'rb')
try:
while True:
emp=pickle.load(fobj)
if emp[2]<175000:
print(emp[0],emp[1],emp[2],emp[3],sep='\t')
found=1
except:
fobj.close()
if found==0:
print('No Records Found in the File!')
Page 6/9
Python Notes Class XII Binary File
elif cho=='0': break
def editrecord():
while True:
print('-- Edit Menu --')
print('1. Edit One Record')
print('2. Edit All Records')
print('0. Return')
cho=input('Choice[0-2]? ')
if cho=='1':
frobj=open('EMPDATA.DAT', 'rb')
fwobj=open('TEMPDATA.DAT', 'wb')
code=int(input('Code to edit? '))
found=0
try:
while True:
emp=pickle.load(frobj)
if code==emp[0]:
print('Current Bsal=',emp[2])
emp[2]=float(input('New BSal? '))
emp[3]=0.2*emp[2]
found=1
pickle.dump(emp, fwobj)
except:
frobj.close()
fwobj.close()
if found==1:
print('Record with code =',code,'is updated!')
else:
print('Code =',code,'not found in the file!')
remove('EMPDATA.DAT')
rename('TEMPDATA.DAT', 'EMPDATA.DAT')
elif cho=='2':
frobj=open('EMPDATA.DAT', 'rb')
fwobj=open('TEMPDATA.DAT', 'wb')
try:
while True:
emp=pickle.load(frobj)
emp[2]+=10000
emp[3]=0.2*emp[2]
pickle.dump(emp, fwobj)
except:
frobj.close()
fwobj.close()
print('All records are updated!')
remove('EMPDATA.DAT')
rename('TEMPDATA.DAT', 'EMPDATA.DAT')
elif cho=='0': break
def delrecord():
while True:
print('-- Delete Menu --')
print('1. Delete by code')
print('2. Delete by name')
Page 7/9
Python Notes Class XII Binary File
print('0. Return')
cho=input('Choice[0-2]? ')
if cho=='1':
frobj=open('EMPDATA.DAT', 'rb')
fwobj=open('TEMPDATA.DAT', 'wb')
code=int(input('Code to delete? '))
found=0
try:
while True:
emp=pickle.load(frobj)
if code==emp[0]:
found=1
else:
pickle.dump(emp, fwobj)
except:
frobj.close()
fwobj.close()
if found==1:
print('Record with code =',code,'is deleted!')
else:
print('Code =',code,'not found in the file!')
remove('EMPDATA.DAT')
rename('TEMPDATA.DAT', 'EMPDATA.DAT')
elif cho=='2':
frobj=open('EMPDATA.DAT', 'rb')
fwobj=open('TEMPDATA.DAT', 'wb')
name=input('Name to delete? ')
found=0
try:
while True:
emp=pickle.load(frobj)
if name.upper()==emp[1]:
found=1
else:
pickle.dump(emp, fwobj)
except:
frobj.close()
fwobj.close()
if found==1:
print('Record with name =',name,'is deleted!')
else:
print('Name =',name,'not found in the file!')
remove('EMPDATA.DAT')
rename('TEMPDATA.DAT', 'EMPDATA.DAT')
elif cho=='0': break;
def sortrecords():
while True:
print('-- Sorting Menu --')
print('1. Sort on Name')
print('2. Sort on BSal')
print('0. To Return')
cho=input('Choice[0-2]? ')
if cho=='1':
Page 8/9
Python Notes Class XII Binary File
fobj=open('EMPDATA.DAT', 'rb')
alist=[]
try:
while True:
emp=pickle.load(fobj)
alist+=[emp]
except:
fobj.close()
n=len(alist)
for k in range(1, n):
for x in range(n-k):
if alist[x][1]>alist[x+1][1]:
alist[x],alist[x+1]=alist[x+1],alist[x]
print('Employee details sorted on Name')
for emp in alist:
print(emp[0],emp[1],emp[2],emp[3],sep='\t')
elif cho=='2':
fobj=open('EMPDATA.DAT', 'rb')
alist=[]
try:
while True:
emp=pickle.load(fobj)
alist+=[emp]
except:
fobj.close()
n=len(alist)
for k in range(1, n):
for x in range(n-k):
if alist[x][2]<alist[x+1][2]:
alist[x],alist[x+1]=alist[x+1],alist[x]
print('Employee details sorted on BSal')
for emp in alist:
print(emp[0],emp[1],emp[2],emp[3],sep='\t')
elif cho=='0': break
Page 9/9