Python Binary Files
Python Binary Files
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.
Python function to append list type data (every record is a list) in a binary data file type is given below:
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, name.upper(), bsal]
pickle.dump(emp, fobj)
fobj.close()
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 data file can store dictionary type data (every record is dictionary type)
also. Python function to append dictionary type data (every record is a dictionary) in a binary data file
type is given below:
import pickle
def addrec():
fobj=open('SALARY.DAT', 'ab')
for k in range(5):
code:int(input('Code? '))
name:input('Name? ').upper()
bsal:float(input('BSal? '))
emp={'co':code, 'na':name, 'bs':bsal}
pickle.dump(emp, fobj)
fobj.close()
Page 1/8
Python Notes Class XII Binary File
Number of load() must match number dump() when reading from a binary data file. Since it
impossible to remember the count, a strategy has to be devised by which there will be no need to remember
number of load() when reading a from a binary file. Python function to read and display a binary data
file containing list type data (every record is a list) is given below:
import pickle
def showrec():
fobj=open('SALARY.DAT', 'rb')
fobj.seek(0, 2)
eof=fobj.tell()
fobj.seek(0)
while fobj.tell()<eof:
emp=pickle.load(fobj)
print(emp[0],emp[1],emp[2],sep='\t')
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. File object method seek() moves the
file pointer and file object method tell() returns the position of the file pointer.
fobj.seek(0, 2): moves the file pointer to the end of the file
eof=fobj.tell(): returns the position of the file pointer at the end of the file (position of the last
byte of the file)
fobj.seek(0) : moves the file pointer to the beginning of the file
The logic for reading a binary file is read all the records of the file till the end of the file. The while loop
condition, fobj.tell()<eof compares current position of the file pointer. If the current position of
the file pointer is less than position of the last byte, it means at least one more record is yet to be read.
After last record has been read, fobj.tell() and eof will be equal. As menitioned earlier, a binary
data may contain dictionary type data. Python function to read and display a binary data file containing
dictionary type data (every record is a dictionary) is given below:
import pickle
def showrec():
fobj=open('SALARY.DAT', 'rb')
fobj.seek(0, 2)
eof=fobj.tell()
fobj.seek(0)
while fobj.tell()<eof:try:
emp=pickle.load(fobj)
print(emp['co'],emp['na'],emp['bs'],sep='\t')
fobj.close()
Function to search for a code in a binary data file containing list type data (every record is a list), using
a flag variable is given below:
import pickle
def searchcode():
fobj=open('SALARY.DAT', 'rb')
fobj.seek(0, 2)
eof=fobj.tell()
fobj.seek(0)
code=int(input('Code to Search? '))
found=0
while fobj.tell()<eof:
emp=pickle.load(fobj)
if code==emp[0]:
Page 2/8
Python Notes Class XII Binary File
print(emp[0],emp[1],emp[2],sep='\t')
found=1
break
fobj.close()
if found==0:
print(code, 'Not Found in the File')
OR,
Function to search for a code in a binary data file containing list type data (every record is a list), without
using a flag variable is given below:
import pickle
def searchcode():
fobj=open('SALARY.DAT', 'rb')
fobj.seek(0, 2)
eof=fobj.tell()
fobj.seek(0)
code=int(input('Code to Search? '))
while fobj.tell()<eof:
emp=pickle.load(fobj)
if code==emp[0]:
print(emp[0],emp[1],emp[2],sep='\t')
found=1
break
else:
print(code, 'Not Found in the File')
fobj.close()
Function to search for name in a binary data file (containing list type of data), using a flag variable is
given below (assuming all names are distinct):
import pickle
def searchname():
fobj=open('SALARY.DAT', 'rb')
fobj.seek(0, 2)
eof=fobj.tell()
fobj.seek(0)
name=input('Name to Search? ').upper()
found=0
while fobj.tell()<eof:
emp=pickle.load(fobj)
if name==emp[1]:
print(emp[0],emp[1],emp[2],sep='\t')
found=1
break
fobj.close()
if found==0:
print(name, 'Not Found in the File')
OR,
Function to search for name in a binary data file (containing list type of data), without using a flag variable
is given below (assuming all names are distinct):
import pickle
def searchname():
fobj=open('SALARY.DAT', 'rb')
fobj.seek(0, 2)
eof=fobj.tell()
fobj.seek(0)
Page 3/8
Python Notes Class XII Binary File
name=input('Name to Search? ').upper()
while fobj.tell()<eof:
emp=pickle.load(fobj)
if name==emp[1]:
print(emp[0],emp[1],emp[2],sep='\t')
found=1
break
else:
print(name, 'Not Found in the File')
fobj.close()
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')
fobj.seek(0, 2)
eof=fobj.tell()
fobj.seek(0)
while fobj.tell()<eof:
emp=pickle.load(fobj)
if emp[2]>150000.0:
print(emp[0],emp[1],emp[2],sep='\t')
c+=1
fobj.close()
print('Number of Records=',c)
OR,
def searchbsal():
fobj=open('SALARY.DAT', 'rb')
fobj.seek(0, 2)
eof=fobj.tell()
fobj.seek(0)
c=0
while fobj.tell()<eof:
emp=pickle.load(fobj)
if emp[2]>150000.0:
print(emp[0],emp[1],emp[2],sep='\t')
c+=1
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) using a temporary file
is given below:
import pickle
from os import remove, rename
def editallrecs():
frobj=open('SALARY.DAT', 'rb')
fwobj=open('TEMP.DAT', 'wb')
frobj.seek(0, 2)
eof=frobj.tell()
frobj.seek(0)
while frobj.tell()<eof:
emp=pickle.load(frobj)
emp[2]+=10000
Page 4/8
Python Notes Class XII Binary File
pickle.dump(emp, fwobj)
frobj.close()
fwobj.close()
remove('SALARY.DAT')
rename('TEMP.DAT','SALARY.DAT')
Function to edit all the records in a binary data file (containing list type of data) using a list is given
below:
import pickle
def editallrecs():
fobj=open('SALARY.DAT', 'rb')
fobj.seek(0, 2)
eof=fobj.tell()
fobj.seek(0)
emplist=[]
while fobj.tell()<eof:
emp=pickle.load(fobj)
emp[2]+=10000
emplist+=[emp]
fobj.close()
fobj=open('SALARY.DAT', 'wb')
for emp in emplist:
pickle.dump(emp, fobj)
fobj.close()
Function to edit a particular record (by inputting employee code) in a binary data file (containing list
type of data) using a temporary file is given below:
import pickle
from os import remove, rename
def editonerec():
frobj=open('SALARY.DAT', 'rb')
fwobj=open('TEMP.DAT', 'wb')
frobj.seek(0, 2)
eof=frobj.tell()
frobj.seek(0)
code=int(input('Input Code to Edit? '))
found=0
while frobj.tell()<eof:
emp=pickle.load(frobj)
if code==emp[0]:
emp[2]+=10000
found=1
pickle.dump(emp, fwobj)
frobj.close()
fwobj.close()
remove('SALARY.DAT')
rename('TEMP.DAT','SALARY.DAT')
if found==1:
print('Record Updated in the File')
else:
print(code, 'Not Found in the File!!')
Function to edit a particular record (by inputting employee code) in a binary data file (containing list
type of data) using a list is given below:
Page 5/8
Python Notes Class XII Binary File
import pickle
def editonerec():
fobj=open('SALARY.DAT', 'rb')
fobj.seek(0, 2)
eof=fobj.tell()
fobj.seek(0)
code=int(input('Input Code to Edit? '))
found=0
emplist=[]
while fobj.tell()<eof:
emp=pickle.load(robj)
if code==emp[0]:
emp[2]+=10000
found=1
emplist+=[emp]
fobj.close()
fobj=open('SALARY.DAT', 'wb')
for emp in emplist:
pickle.dump(emp, fobj)
fobj.close()
if found==1:
print('Record Updated in the File')
else:
print(code, 'Not Found in the File!!')
Function to delete a record from a binary data file (containing list type of data) using a temporary file is
given below:
import pickle
from os import remove, rename
def deleterecord():
frobj=open('SALARY.DAT', 'rb')
fwobj=open('TEMP.DAT', 'wb')
frobj.seek(0, 2)
eof=frobj.tell()
frobj.seek(0)
code=int(input('Code to Delete? '))
found=0
while frobj.tell()<eof:
emp=pickle.load(frobj)
if code==emp[0]:
found=1
else:
pickle.dump(emp, fwobj)
frobj.close()
fwobj.close()
remove('SALARY.DAT')
rename('TEMP.DAT','SALARY.DAT')
if found==1:
print('Record Deleted From the File')
else:
print(code, 'Not Found in the File')
Function to delete a record from a binary data file (containing list type of data) using a list is given below:
import pickle
Page 6/8
Python Notes Class XII Binary File
def deleterecord():
fobj=open('SALARY.DAT', 'rb')
fobj.seek(0, 2)
eof=fobj.tell()
fobj.seek(0)
code=int(input('Code to Delete? '))
found=0
emplist=[]
while fobj.tell()<eof:
emp=pickle.load(fobj)
if code==emp[0]:
found=1
else:
emplist+=[emp]
fobj.close()
fobj=open('SALARY.DAT', 'wb')
for emp in emplist:
pickle.dump(emp, fobj)
fobj.close()
if found==1:
print('Record Deleted From the File')
else:
print(code, 'Not Found in the File')
Page 7/8
Python Notes Class XII Binary File
Running of the program produces following output:
2003 JATHIN KUMAR 155000.0 31000.0 186000.0
2006 TINA DASH 155000.0 31000.0 186000.0
2010 MITALI JHA 160000.0 32000.0 192000.0
2008 DILIP SHAW 155000.0 31000.0 186000.0
Page 8/8