Python Pickle: Python Notes Class XII Binary File
Python Pickle: Python Notes Class XII Binary File
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')
n=int(input('Number of Records? '))
for k in range(n):
code=int(input('Code? '))
name=input('Name? ').upper()
bsal=float(input('BSal? '))
emp=[code, name, bsal]
pickle.dump(emp, fobj)
fobj.close()
Variable fobj is a file object created with built-in function open(). File mode contains 2-characters
string. Letter 'a' for append mode and letter 'b' for binary. Order of the two letters does not really
matter. 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 will be a list). Statement pickle.dump(emp, fobj) writes a
record into a binary file data file through a buffer. One record is written at a time in the binary data file.
Either in a text file or a CSV file (also a text file), reading beyond the end of a file is not an issue. In a text
file, reading beyond a text file will return an empty string (using read() / readline() method) or an empty
list (using readlines() method). In a CSV file, reding beyond CSV will return an empty list. But in a binary
data file, reading beyond the end of the file will trigger a run-time error. So when reading from a binary
data file, one has to remember number of dump() and it has to match number of load(). Since it
practically impossible to remember the count, a strategy has to be devised by which there will be no need
to remember number of dump() when reading records a from a binary data file. There are couple of ways
doing it. First is using file pointer and second is using try-except (will be discussed later, after the summer
break). Python function to read and display a binary data file containing list type data (every record is a
list) using a file pointer is given in the next page:
Page 1/25
Python Notes Class XII Binary File
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.
The logic for reading a binary file is to read all the records of the binary file till the end of the file. The
while loop condition, fobj.tell()<eof compares current position of the file pointer with the position
of the file pointer at the end of the file. 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 are equal (current position of the file pointer is equal to position of the file
pointer at the end of the file). That is, all records have been read, while condition is False, end of the loop.
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 In the while loop block, break
def searchcode(): statement is optional. Generally,
fobj=open('SALARY.DAT', 'rb') employee code is unique, if the
fobj.seek(0, 2) inputted code is located in the file,
eof=fobj.tell()
no need to search any more record,
fobj.seek(0)
code=int(input('Code to Search? ')) break statement will terminate the
found=0 loop. If the break statement is
while fobj.tell()<eof: removed, all the records will be
emp=pickle.load(fobj) read, whether inputted employee
if code==emp[0]: code is found or not. Checking the
print(emp[0],emp[1],emp[2],sep='\t') status of the flag variable found,
found=1 will display a message when code
break is not found in the file.
fobj.close()
if found==0:
print(code, 'Not Found in the File')
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)
Page 2/25
Python Notes Class XII Binary File
eof=fobj.tell()
In the while loop block, break
fobj.seek(0)
code=int(input('Code to Search? ')) statement is mandatory. Since else
while fobj.tell()<eof: part of the while loop only gets
emp=pickle.load(fobj) executed when while loop ends
if code==emp[0]: normally. In this case, when inputted
print(emp[0],emp[1],emp[2],sep='\t') employee code could not be located
found=1 in the file. If the inputted employee
break code is found in the file, break
else: statements ends the while loop, else
print(code, 'Not Found in the File') part does not get executed.
fobj.close()
Function to search for name in a binary data file (containing list type of record), using a flag variable is
given below:
This code will work correctly, if no
import pickle
def searchname(): name is repeated in the file. If a name
fobj=open('SALARY.DAT', 'rb') is repeated in the file, this code will
fobj.seek(0, 2) display the first occurrence of the
eof=fobj.tell() name. To display all the names,
fobj.seek(0) present in the file, break statement has
name=input('Name to Search? ').upper() to be removed from the while loop. As
found=0 mentioned earlier, break statement
while fobj.tell()<eof: can be removed completely.
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')
Function to search for name in a binary data file (containing list type of record), without using a flag
variable is given below:
This code will work correctly, if no
import pickle
def searchname(): name is repeated in the file. If a name
fobj=open('SALARY.DAT', 'rb') is repeated in the file, this code will
fobj.seek(0, 2) display the first occurrence of the
eof=fobj.tell() name. By removing break statement
fobj.seek(0) from while loop, else part will be
name=input('Name to Search? ').upper() executed every time, whether inputted
while fobj.tell()<eof: name is found or not.
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 (bsal exceeds 150000.0) in a binary data file (containing list type of record)
is given in the next page:
Page 3/25
Python Notes Class XII Binary File
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 search for salary (bsal) in a binary data file where salary read from the file exceeds an inputted
salary (containing list type of record) is given below:
import pickle
def searchbsal():
fobj=open('SALARY.DAT', 'rb')
fobj.seek(0, 2)
eof=fobj.tell()
fobj.seek(0)
bsal=float(input('Salary to search? '))
while fobj.tell()<eof:
emp=pickle.load(fobj)
if emp[2]>bsal:
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
bsal=float(input('Salary to search? '))
while fobj.tell()<eof:
emp=pickle.load(fobj)
Page 4/25
Python Notes Class XII Binary File
if emp[2]>bsal:
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, os
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
pickle.dump(emp, fwobj)
frobj.close()
fwobj.close()
os.remove('SALARY.DAT')
os.rename('TEMP.DAT','SALARY.DAT')
Function to edit all the records in a binary data file (containing list type of data) using a nested list is
given below:
import pickle
def editallrecs():
frobj=open('SALARY.DAT', 'rb')
fwobj=
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()
with open('SALARY.DAT', 'wb') as fobj:
for emp in emplist: pickle.dump(emp, fobj)
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, os
def editallrecs():
frobj=open('SALARY.DAT', 'rb')
fwobj=open('TEMP.DAT', 'wb')
fobj.seek(0, 2)
eof=fobj.tell()
fobj.seek(0)
emplist=[]
while fobj.tell()<eof:
emp=pickle.load(fobj)
Page 5/25
Python Notes Class XII Binary File
emp[2]+=10000
fwobj.dump(emp, fwobj)
frobj.close()
fwobj.close()
os.remove('SALARY.DAT')
os.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) using a temporary file is given below:
import pickle, os
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
print('Record Updated in the File')
pickle.dump(emp, fwobj)
frobj.close()
fwobj.close()
if found==0: print(code, 'Not Found in the File!!')
os.remove('SALARY.DAT')
os.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) using a list is given below:
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
print('Record Updated in the File')
found=1
emplist+=[emp]
fobj.close()
with open('SALARY.DAT', 'wb') as fobj;
for emp in emplist: pickle.dump(emp, fobj)
if found==0: print(code, 'Not Found in the File!!')
Page 6/25
Python Notes Class XII Binary 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, os
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]:
print('Record Deleted From the File')
found=1
else:
pickle.dump(emp, fwobj)
frobj.close()
fwobj.close()
if found==0: print(code, 'Not Found in the File')
os.remove('SALARY.DAT');
os.rename('TEMP.DAT','SALARY.DAT')
Function to delete a record from a binary data file (containing list type of data) using a list is given below:
import pickle
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
print('Record Deleted From the File')
else:
emplist+=[emp]
fobj.close()
with open('SALARY.DAT', 'wb') as fobj:
for emp in emplist: pickle.dump(emp, fobj)
if found==0: print(code, 'Not Found in the File')
Page 7/25
Python Notes Class XII Binary File
File Pointer and Binary File
Now with binary file we will see the use of seek(pos, whence). Binary data file 'EMPSAL.DAT'
contains records as [CODE, NAME, BSAL, HRA, GSAL].
Content of EMP.DAT with the position of file pointer after every record:
2001 GUATAM SHARMA 155000.0 31000.0 186000.0 62
2002 DEEPIKA RAO 166000.0 33200.0 199200.0 122
2003 JATHIN KUMAR 155000.0 31000.0 186000.0 183
2004 ADITI GUPTA 150000.0 30000.0 180000.0 243
2005 ASEEM KAPUR 170000.0 34000.0 204000.0 303
2006 TINA DASH 155000.0 31000.0 186000.0 361
2007 KUNAL THAKUR 155000.0 31000.0 186000.0 422
2008 DILIP SHAW 155000.0 31000.0 186000.0 481
2009 JYOTHI SURESH 185000.0 37000.0 222000.0 543
2010 MITALI JHA 160000.0 32000.0 192000.0 602
import pickle
fobj=open('EMP.DAT','rb')
fobj.seek(122)
emp=pickle.load(fobj)
print(emp[0],emp[1],emp[2],sep='\t')
fobj.seek(120,1)
emp=pickle.load(fobj)
print(emp[0],emp[1],emp[2],sep='\t')
fobj.seek(182,1)
emp=pickle.load(fobj)
print(emp[0],emp[1],emp[2],sep='\t')
fobj.seek(-180,2)
emp=pickle.load(fobj)
print(emp[0],emp[1],emp[2],sep='\t')
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:
pass
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
except:
pass
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? ')
Page 9/25
Python Notes Class XII Binary File
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:
pass
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:
pass
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:
pass
fobj.close()
if found==0: print('No Records Found in the File!')
elif cho=='0': break
def editrecord():
while True:
print('-- Edit Menu --')
print('1. Edit One Record')
print('2. Edit All Records')
Page 10/25
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 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]
print('Record with code =',code,'is updated!')
found=1
pickle.dump(emp, fwobj)
except:
pass
frobj.close()
fwobj.close()
if found==0: print('Code =',code,'not found in the file!')
os.remove('EMPDATA.DAT')
os.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:
pass
frobj.close()
fwobj.close()
print('All records are updated!')
os.remove('EMPDATA.DAT')
os.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')
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
Page 11/25
Python Notes Class XII Binary File
try:
while True:
emp=pickle.load(frobj)
if code==emp[0]:
print('Record with code =',code,'is deleted!')
found=1
else:
pickle.dump(emp, fwobj)
except:
pass
frobj.close()
fwobj.close()
if found==0: print('Code =',code,'not found in the file!')
os.remove('EMPDATA.DAT')
os.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]:
print('Record with name =',name,'is deleted!')
found=1
else:
pickle.dump(emp, fwobj)
except:
pass
frobj.close()
fwobj.close()
if found==0: print('Name =',name,'not found in the file!')
os.remove('EMPDATA.DAT')
os.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]? ')
alist=[]
if cho=='1':
fobj=open('EMPDATA.DAT', 'rb')
try:
while True:
emp=pickle.load(fobj)
alist+=[emp]
except:
pass
fobj.close()
Page 12/25
Python Notes Class XII Binary File
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')
try:
while True:
emp=pickle.load(fobj)
alist+=[emp]
except:
pass
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
We have used a list to store (write / append) a record in a binary file. But instead of using a list, we may
use a dictionary to store (write / append) a record in a binary file. Functions are given below using
dictionary for appending records in a binary file, reading records from a binary file, searching for
records(s) stored in a binary file, updating record(s) stored in a binary file and deleting record(s) from a
binary.
import pickle, os
def addemprec():
fobj=open('EMPDATA.DAT', 'ab')
Page 13/25
Python Notes Class XII Binary File
n=int(input('Number of records? '))
for x in range(n):
emp={
'code':int(input('Code? ')),
'name':input('Name? ').upper(),
'bsal':float(input('BSal? '))
}
pickle.dump(emp, fobj)
fobj.close()
def reademprec():
fobj=open('EMPDATA.DAT', 'rb')
fobj.seek(0, 2)
eof=fobj.tell()
fobj.seek(0)
while fobj.tell()<eof:
rec=pickle.load(fobj)
print(rec['code'], rec['name'], rec['bsal'], sep='\t')
fobj.close()
def searchcode():
fobj=open('EMPDATA.DAT', 'rb')
fobj.seek(0, 2)
eof=fobj.tell()
fobj.seek(0)
code=int(input('Code to Search? '))
found=0
while fobj.tell()<eof:
rec=pickle.load(fobj)
if code==rec['code']:
print(rec['code'], rec['name'], rec['bsal'], sep='\t')
found=1
break
fobj.close()
if found==0: print(code, 'Not Found in the File!!')
OR,
def searchcode():
fobj=open('EMPDATA.DAT', 'rb')
fobj.seek(0, 2)
eof=fobj.tell()
fobj.seek(0)
code=int(input('Code to Search? '))
while fobj.tell()<eof:
rec=pickle.load(fobj)
if code==rec['code']:
print(rec['code'], rec['name'], rec['bsal'], sep='\t')
break
else:
print(code, 'Not Found in the File!!')
fobj.close()
def searchbsal():
fobj=open('EMPDATA.DAT', 'rb')
fobj.seek(0, 2)
Page 14/25
Python Notes Class XII Binary File
eof=fobj.tell()
fobj.seek(0)
found=0
while fobj.tell()<eof:
rec=pickle.load(fobj)
if 120000.0<=rec['bsal']<=140000.0:
print(rec['code'], rec['name'], rec['bsal'], sep='\t')
found=1
fobj.close()
if found==0: print('No Record Found in the File!!')
def updatebsalall():
frobj=open('EMPDATA.DAT', 'rb')
fwobj=open('TEMP.DAT', 'wb')
frobj.seek(0, 2)
eof=frobj.tell()
frobj.seek(0)
while frobj.tell()<eof:
rec=pickle.load(frobj)
rec['bsal']+=5000
pickle.dump(rec, fwobj)
frobj.close()
fwobj.close()
os.remove('EMPDATA.DAT')
os.rename('TEMP.DAT','EMPDATA.DAT')
print('All records have been updated!!')
def updatebsal():
frobj=open('EMPDATA.DAT', 'rb')
fwobj=open('TEMP.DAT', 'wb')
frobj.seek(0, 2)
eof=frobj.tell()
frobj.seek(0)
code=int(input('Code to Edit? '))
found=0
while frobj.tell()<eof:
rec=pickle.load(frobj)
if code==rec['code']:
rec['bsal']+=5000
found=1
print('Record Updated!')
pickle.dump(rec, fwobj)
frobj.close()
fwobj.close()
os.remove('EMPDATA.DAT')
os.rename('TEMP.DAT','EMPDATA.DAT')
if found==0: print(code, 'Not Found in the File!!')
def deleterec():
frobj=open('EMPDATA.DAT', 'rb')
fwobj=open('TEMP.DAT', 'wb')
frobj.seek(0, 2)
eof=frobj.tell()
frobj.seek(0)
Page 15/25
Python Notes Class XII Binary File
code=int(input('Code to Delete? '))
found=0
while frobj.tell()<eof:
rec=pickle.load(frobj)
if code==rec['code']:
found=1
print('Record Deleted!')
else:
pickle.dump(rec, fwobj)
frobj.close()
fwobj.close()
os.remove('EMPDATA.DAT')
os.rename('TEMP.DAT','EMPDATA.DAT')
if found==0: print(code, 'Not Found in the File!!')
Instead of using a list or a dictionary to stored records in a binary file, we may use a nested list to store
records in a binary. Advantages of nested list to store records in binary file are:
All the records can be stored using single dump() function
All the records can be read using single load() function
Complete menu driven program is given below showing how to use nested list to store / read / search /
edit / delete records using nested list.
import pickle
def addrecord():
fobj=open('STUDENT.DAT', 'ab+')
if fobj.tell()==0:
stulist=[]
else:
fobj.seek(0)
stulist=pickle.load(fobj)
n=int(input('Records to Append? '))
for x in range(n):
roll=int(input('Roll? '))
name=input('Name? ').upper()
theo=float(input('Theo? '))
stulist+=[[roll,name,theo]]
fobj.seek(0)
fobj.truncate()
pickle.dump(stulist, fobj)
fobj.close()
def readrecord():
fobj=open('STUDENT.DAT', 'rb')
stulist=pickle.load(fobj)
fobj.close()
for stu in stulist: print(stu[0],stu[1],stu[2])
def searchroll():
fobj=open('STUDENT.DAT', 'rb')
stulist=pickle.load(fobj)
fobj.close()
roll=int(input('Roll to Search? '))
for stu in stulist:
if roll==stu[0]:
print(f'Roll ={stu[0]}')
Page 16/25
Python Notes Class XII Binary File
print(f'Name ={stu[1]}')
print(f'Theory={stu[2]}')
break
else: print(f'Roll={roll} Not Found!')
def searchname():
fobj=open('STUDENT.DAT', 'rb')
stulist=pickle.load(fobj)
fobj.close()
name=input('Name to Search? ').upper()
for stu in stulist:
if name==stu[1]:
print(f'Roll ={stu[0]}')
print(f'Name ={stu[1]}')
print(f'Theory={stu[2]}')
break
else: print(f'Name={name} Not Found!')
def searchtheo():
fobj=open('STUDENT.DAT', 'rb')
stulist=pickle.load(fobj)
fobj.close()
found=0
for stu in stulist:
if stu[2]>=60:
print(stu[0],stu[1],stu[2])
found=1
if found==0: print('No Record Found!')
def editallrec():
fobj=open('STUDENT.DAT', 'rb+')
stulist=pickle.load(fobj)
for stu in stulist:
stu[2]+=2
fobj.seek(0)
fobj.truncate()
pickle.dump(stulist, fobj)
fobj.close()
print('All Records Updated')
def editonerec():
fobj=open('STUDENT.DAT', 'rb+')
stulist=pickle.load(fobj)
roll=int(input('Roll to Edit? '))
for stu in stulist:
if roll==stu[0]:
stu[2]+=2
print('Record Updated')
break
else:
print(f'Roll={roll} Not Found!')
fobj.close()
return
fobj.seek(0)
Page 17/25
Python Notes Class XII Binary File
fobj.truncate()
pickle.dump(stulist, fobj)
fobj.close()
def deleterec():
fobj=open('STUDENT.DAT', 'rb+')
stulist=pickle.load(fobj)
roll=int(input('Roll to Delete? '))
for stu in stulist:
if roll==stu[0]:
stulist.remove(stu)
print('Record Deleted')
break
else:
print(f'Roll={roll} Not Found!')
fobj.close()
return
fobj.seek(0)
fobj.truncate()
pickle.dump(stulist, fobj)
fobj.close()
#--------------- Main ---------------
while True:
print('---- Main Menu ----')
print('1. Add Records')
print('2. Display Records')
print('3. Search Records')
print('4. Update Records')
print('5. Delete Record')
print('0. Exit')
ch=input('Choice[0-5]? ')
if ch=='1': addrecord()
elif ch=='2': readrecord()
elif ch=='3':
while True:
print('---- Search Menu ----')
print('1. Search Roll')
print('2. Search Name')
print('3. Search Theo')
print('0. Return to Main')
ch2=input('Choice[0-3]? ')
if ch2=='1': searchroll()
elif ch2=='2': searchname()
elif ch2=='3': searchtheo()
elif ch2=='0': break
elif ch=='4':
while True:
print('---- Update Menu ----')
print('1. Edit All')
print('2. Edit By Roll')
print('0. Return to Main')
ch2=input('Choice[0-2]? ')
if ch2=='1': editallrec()
elif ch2=='2': editonerec()
Page 18/25
Python Notes Class XII Binary File
elif ch2=='0': break
elif ch=='5': deleterec()
elif ch=='0': break
Python menu driven binary file program using try-except is given below:
import pickle, os
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? ').upper()
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')
while True:
try:
emp=pickle.load(fobj)
print(emp[0],emp[1],emp[2],emp[3],sep='\t')
except:
break
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? '))
while True:
try:
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
except:
break
Page 19/25
Python Notes Class XII Binary File
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? ')
while True:
try:
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
except:
break
if found==0: print('Name =',name,'Not found in the file!')
elif cho=='3':
fobj=open('EMPDATA.DAT', 'rb')
while True:
try:
emp=pickle.load(fobj)
if emp[2]>150000:
print(emp[0],emp[1],emp[2],emp[3],sep='\t')
found=1
except:
break
fobj.close()
if found==0: print('No Records Found in the File!')
elif cho=='4':
fobj=open('EMPDATA.DAT', 'rb')
while True:
try:
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:
break
fobj.close()
if found==0: print('No Records Found in the File!')
elif cho=='5':
fobj=open('EMPDATA.DAT', 'rb')
while True:
try:
emp=pickle.load(fobj)
if emp[2]<175000:
print(emp[0],emp[1],emp[2],emp[3],sep='\t')
found=1
except:
break
if found==0: print('No Records Found in the File!')
Page 20/25
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
while True:
try:
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
print('Record with code =',code,'is updated!')
pickle.dump(emp, fwobj)
except:
break
frobj.close()
fwobj.close()
if found==0: print('Code =',code,'not found in the file!')
os.remove('EMPDATA.DAT')
os.rename('TEMPDATA.DAT', 'EMPDATA.DAT')
elif cho=='2':
frobj=open('EMPDATA.DAT', 'rb')
fwobj=open('TEMPDATA.DAT', 'wb')
while True:
try:
emp=pickle.load(frobj)
emp[2]+=10000
emp[3]=0.2*emp[2]
pickle.dump(emp, fwobj)
except:
break
frobj.close()
fwobj.close()
print('All records are updated!')
os.remove('EMPDATA.DAT')
os.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 21/25
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
while True:
try:
emp=pickle.load(frobj)
if code==emp[0]:
found=1
print('Record with code =',code,'is deleted!')
else:
pickle.dump(emp, fwobj)
except:
break
frobj.close()
fwobj.close()
if found==0: print('Code =',code,'not found in the file!')
os.remove('EMPDATA.DAT')
os.rename('TEMPDATA.DAT', 'EMPDATA.DAT')
elif cho=='2':
frobj=open('EMPDATA.DAT', 'rb')
fwobj=open('TEMPDATA.DAT', 'wb')
name=input('Name to delete? ').upper()
found=0
while True:
try:
emp=pickle.load(frobj)
if name==emp[1]:
found=1
print('Record with name =',name,'is deleted!')
else:
pickle.dump(emp, fwobj)
except:
break
frobj.close()
fwobj.close()
if found==0: print('Name =',name,'not found in the file!')
os.remove('EMPDATA.DAT')
os.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':
fobj=open('EMPDATA.DAT', 'rb')
alist=[]
Page 22/25
Python Notes Class XII Binary File
while True:
try:
emp=pickle.load(fobj)
alist+=[emp]
except:
break
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=[]
while True:
try:
emp=pickle.load(fobj)
alist+=[emp]
except:
break
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 23/25
Python Notes Class XII Binary File
Standard Input and Standard Output
Standard input: input from standard device connected to a computer, that is input from keyboard. Every
input from a keyboard is either a string of list of string.
Standard output: output to standard device connected to a computer, that is output to screen. Either a
string or a list of strings is display on the monitor.
Module sys is needed to input using standard input device and to display using standard output device.
Using readline() – unlimited string input from the keyboard, till user types
>>> import sys
>>> fruits=sys.stdin.readline()
APPLE, GUAVA, MANGO, ORNAGE, APPLE, BANANA # to terminate input
>>> print(fruits) #displays the entire inputted string
APPLE, GUAVA, MANGO, ORNAGE, APPLE, BANANA
Using readlines() – unlimited multi-line string input from the keyboard and inputs are stored in a list
of strings (each line is a string), till user types ^D
>>> import sys
>>> text=sys.stdin.readlines()
Kuwait has extended lock down till 26-April.
Curfew hours have been extended from 5:00PM to 6:00AM.
However, expats are allowed to leave Kuwait.
^D #to terminate input
>>> print(text)
['Kuwait has extended lock down till 26-April.\n', 'Curfew hours have
been extended from 5:00PM to 6:00AM.\n', 'However, expats are allowed
to leave Kuwait.\n']
>>> for line in text: print(line.strip())
Kuwait has extended lock down till 26-April.
Curfew hours have been extended from 5:00PM to 6:00AM.
However, expats are allowed to leave Kuwait.
Page 24/25
Python Notes Class XII Binary File
Display data using standard input
Using write() and writelines()
>>> import sys
>>> school='FAIPS, DPS-Kuwait'
>>> sys.stdout.write(school)
FAIPS, DPS-Kuwait17
17 number of characters displayed on the screen in the Python’s IDEL, number will not be displayed
in the Python's script mode.
>>> sys.stdout.writelines(school)
FAIPS, DPS-Kuwait
Only the string is displayed on the screen without any number.
Page 25/25