0% found this document useful (0 votes)
87 views

Binary File Handling

The document discusses binary file processing in Python. It describes that binary files store data in the same format as it is held in memory without any encoding or translation. This makes binary files faster to read and write than text files but also means they are not human-readable. The key steps for binary file processing are importing the pickle module, opening the file in binary mode, using pickle methods to read/write objects, and closing the file.

Uploaded by

Aryan Baibaswata
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
87 views

Binary File Handling

The document discusses binary file processing in Python. It describes that binary files store data in the same format as it is held in memory without any encoding or translation. This makes binary files faster to read and write than text files but also means they are not human-readable. The key steps for binary file processing are importing the pickle module, opening the file in binary mode, using pickle methods to read/write objects, and closing the file.

Uploaded by

Aryan Baibaswata
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 73

Binary File

Processing
Binary File Processing
In Python a set of logically related data items, describing an entity is
stored in the form of non-simple 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
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 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.
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 The list object studrec is written into the file using dump()
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.
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]
pickle.dump(dets,file)
ans=input("Want to enter another (y/n) - ")
if ans in "nN":
break
file.close()
Record of one student is combined into the list object dets and then written into the
Binary file record by record
Writing record as nested List object to a Binary
Example :
file
WAP to create a binary file student.dat by accepting students records
(roll_no, name, percentage and stream) from the user till user wants.
Program - import pickle
fobj = open("stud.dat","wb")
strecs = [] #Empty list object created
while True:
rno = int(input("\nEnter roll no -"))
name = input("enter name- ")
perc = float(input("Enter Perc -"))
str = input("Enter stream -")
strecs += [[rno,name,perc,str]] #Student record as a nested list
ans = input("Want to enter another (y/n) - ")
if ans in "nN":
break
pickle.dump(strecs,fobj) #Nested List object strecs written into file
The students records are accepted & combined into the nested list object strecs inside
the loop and then written into the file outside the loop in one go.
Reading Binary File
The load() method is used to read (unpickling) data from a binary file. The file
to be loaded is 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, then
pickle.load(file_object) will read a dictionary 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
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 Binary file stud.dat with exception handler
fin=open("stud.dat","rb")
try:
while True:
studrecs = pickle.load(fin)
print(studrecs)
except EOFError:
fin.close()
As while creating stud.dat, each record was written as one list object, while reading each
record is also read as a list object
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])
print("Price - ",itrec[2])
itrec = pickle.load(fin)
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")
temp = open("temp.dat","wb")
sino = int(input("Enter Item no to edit -"))
found = "n"
try:
while True:
Itrec = pickle.load(file)
temprec = itrec
if itrec[0] == sino:
temprec[1] = input("Enter edited name -")
temprec[2] = float(input("Enter edited Price -"))
temprec[3]=int(input("Enter edited quantity in stock -"))
found="y"
pickle.dump(temprec,temp)
except EOFError:
file.close()
temp.close()
if found == "n":
print("No such record")
remove('temp.dat')
else:
remove('item.dat')
rename('temp.dat','item.dat')
Binary File Manipulation
def editonrec():
file = open("item.dat","rb")
temp = open("temp.dat","wb")
er = int(input("Enter record no to edit -"))
found,currec = "n“,0
try:
while True:
Itrec = pickle.load(file)
temprec = itrec
currec+=1
if er == currec:
temprec[1] = input("Enter edited name -")
temprec[2] = float(input("Enter edited Price -"))
temprec[3]=int(input("Enter edited quantity in stock -"))
found="y"
pickle.dump(temprec,temp)
except EOFError:
file.close()
temp.close()
if found == "n":
print("No such record")
remove('temp.dat')
else:
remove('item.dat')
rename('temp.dat','item.dat')
Binary File Manipulation
def editoninm():
file = open("item.dat","rb")
temp = open("temp.dat","wb")
sinm = input("Enter Item name to edit -")
found="n"
try:
while True:
itrec = pickle.load(file)
temprec = itrec
if itrec[1] == sinm:
temprec[2] = float(input("Enter edited Price - "))
temprec[3] = int(input("Enter edited Quqntity - "))
found = "y"
pickle.dump(temprec,temp)
except EOFError:
file.close()
temp.close()
if found=="n":
print("No such record")
remove('temp.dat')
else:
remove('item.dat')
rename('temp.dat','item.dat')
def insertatnth():
Binary File Manipulation
file = open("item.dat","rb")
temp = open("temp.dat","wb")
recno = int(input("Enter record no position -"))
ctr=0
ino = int(input("\nEnter item no -"))
name = input("enter name- ")
price = float(input("Enter Price -"))
qty = int(input("Enter Stock Quantity -"))
newrec = [ino,name,price,qty] #Record to be inserted
try:
while True:
itrec = pickle.load(file)
ctr+=1
if ctr == recno:
pickle.dump(newrec,temp) #new record written
pickle.dump(itrec,temp)
except EOFError:
file.close()
temp.close()
remove('item.dat')
rename('temp.dat','item.dat')
Binary File Manipulation
def insertitno(): #insertion before item no
file = open("item.dat","rb")
temp = open("temp.dat","wb")
sino = int(input("Enter item no -"))
ino = int(input("\nEnter item no -"))
name = input("enter name- ")
price = float(input("Enter Price -"))
qty = int(input("Enter Stock Quantity -"))
newrec = [ino,name,price,qty] #Record to be inserted
try:
while True:
itrec = pickle.load(file)
if itrec[0] == sino:
pickle.dump(newrec,temp) #new record written
pickle.dump(itrec,temp)
except EOFError:
file.close()
temp.close()
remove('item.dat')
rename('temp.dat','item.dat')
Binary File Manipulation
def delnth():
file = open("item.dat","rb")
temp = open("temp.dat","wb")
recno = int(input("Enter record no to delete -"))
ctr = 0
try:
while True:
itrec = pickle.load(file)
ctr += 1
if ctr == recno:
print("record to be deleted")
print(itrec)
else:
pickle.dump(itrec,temp)
except EOFError:
file.close()
temp.close()
remove('item.dat')
rename('temp.dat','item.dat')
Binary File Manipulation
def delitno():
file = open("item.dat","rb")
temp = open("temp.dat","wb")
sino = int(input("Enter Item no to delete -"))
found = "n"
try:
while True:
itrec = pickle.load(file)
if itrec[0] == sino:
print("record to be deleted")
print(itrec)
found="y"
else:
pickle.dump(itrec,temp)
except EOFError:
file.close()
temp.close()
if found =="y":
remove('item.dat')
rename('temp.dat','item.dat')
else:
remove('temp.dat')
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 I
tem name\n8. Insert at nth position\n9.Delete nth\ record\n10. Delete on 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() delnth()
elif ch==3: elif ch==10:
srchino() delitno()
elif ch==4: else:
srchinm() print("wrong choice")
elif ch==5:
sumitemvalues() ans=input("\n want to continue(y/n)")
elif ch==6: if ans in "nN"):
editonino() break
Binary File Manipulation (nested List)
Example : import pickle
Write a menu driven program to create the from os import remove, rename
file stud.dat and perform the following def create():
operations on user’s given choice. Each fobj = open("stud.dat","wb")
record of stud.dat has rollno, name, %age studdets=[]
and stream which is represented as an
while True:
element of nested list
rno = int(input("\nEnter roll no -"))
1. create student File
name = input("enter name- ")
2. Display all student records
perc = float(input("Enter Perc -"))
3. count total records stored in the file
str = input("Enter stream -")
4. count student records for perc >= given
studdets += [[rno,name,perc,str]]
perc
5. search on roll no ans = input("Want to add more")
6. search on name if ans in ("n","N"):
7. count on stream break
8. Edit on roll no pickle.dump(studdets,fobj)
fobj.close()
Binary File Manipulation (nested List)
def display():
fin = open("stud.dat","rb")
try:
studrecs = pickle.load(fin) def countstream():
for r in studrecs: fin = open("stud.dat","rb")
print(r) strctr=0
except EOFError: strnm = input("Enter stream name - ")
fin.close() try:
def countall(): studrecs = pickle.load(fin)
fin = open("stud.dat","rb") for r in studrecs:
ctr=0 if r[3] == strnm:
try: strctr+=1
studrecs = pickle.load(fin) except EOFError:
for r in studrecs:
fin.close()
ctr+=1
print(“Total strudents = ",strctr)
except EOFError:
fin.close()
print("No of Records",ctr)
Binary File Manipulation (nested List)
def display():
fin = open("stud.dat","rb)
ctr=0
try: def countstream():
studrecs = pickle.load(fin) fin = open("stud.dat","rb")
for r in studrecs: strctr=0
print(r) strnm = input("Enter stream name - ")
except EOFError: try:
fin.close() studrecs = pickle.load(fin)
def countall(): for r in studrecs:
fin = open("stud.dat","rb") if r[3] == strnm:
ctr=0 strctr+=1
try: except EOFError:
studrecs = pickle.load(fin)
fin.close()
for r in studrecs:
print(“Total strudents = ",strctr)
ctr+=1
except EOFError:
fin.close()
print("No of Records",ctr)
Binary File Manipulation (nested List)
def searchrno(): def searchname():
fin = open("stud.dat","rb") fin = open("stud.dat","rb)
srno = int(input("Enter rno to search - ")) found="n"
try: srnm = input("Enter name to search - ")
studrecs = pickle.load(fin) try:
for r in studrecs: studrecs = pickle.load(fin)
if r[0] == srno: for r in studrecs:
if r[1] == srnm:
print("Name - ",r[1])
print("Roll no- ",r[0])
print("Percentage - ",r[2]) print("Percentage - ",r[2])
print("Stream - ",r[3]) print("Stream - ",r[3])
break found="y"
else: except EOFError:
print("no such record") fin.close()
except EOFError: if found=="n":
print("No such record")
fin.close()
Binary File Manipulation (nested List)
def dispcountperc(): def updaterno():
fin = open("stud.dat","rb") fin = open("stud.dat","rb+")
ctr=0 srno = int(input("Enter rno to edit - "))
sperc = float(input("Enter %age - ")) try:
try: studrecs = pickle.load(fin)
studrecs = pickle.load(fin) for r in studrecs:
for r in studrecs: if r[0] == srno:
if r[2] >= sperc: r[1] = input("Enter name -")
print("Roll no- ",r[0]) r[2] = float(input("Enter %age-"))
print("Name - ",r[1]) r[3] = input("Enter stream -")
print("Percentage - ",r[2]) found="y"
print("Stream - ",r[3]) break
ctr+=1 except EOFError:
if found == “y”;
except EOFError:
fin.seek(0)
fin.close()
pickle.dump(studrecs,fin)
print("\nTotal No of strudents = ",ctr)
print("data updated in file")
fin.close()
Binary File Manipulation (nested List)
def insertrno():
fin = open("stud.dat","rb+") def updaterno():
srno= int(input(Enter roll no to add)) fin = open("stud.dat","rb+")
ctr , found = 0,”n”
try:
recno = int(input("Enter rec no to edit - "))
studrecs = pickle.load(fin) ctr=0
for r in studrecs: try:
ctr+=1 studrecs = pickle.load(fin)
if r[0] == srno: for r in studrecs:
rno=int(input("\nEnter rollno -")) ctr +=1
name=input("enter name- ")
perc=float(input("Enter Perc -"))
if ctrr == recno:
str=input("Enter stream -") r[1] = input("Enter name -")
newdets=[rno,name,perc,str] r[2] = float(input("Enter %age-"))
studrecs.insert(ctr-1,newdets) r[3] = input("Enter stream -")
found = “y” found="y"
break break
else:
except EOFError:
print(“rec not found”)
if found==“y”: fin.seek(0)
fin.seek(0) pickle.dump(studrecs,fin)
pickle.dump(studrecs,fin) print("data updated in file")
except EOFError: fin.close()
fin.close()
Binary File Manipulation (nested List)
def insertnth(): def deletenth():
print("Enter the Record to be inserted") fin = open("stud.dat","rb+")
rno=int(input("\nEnter roll no -")) pos = int(input("Enter rec no to delete - "))
name=input("enter name- ") try:
perc=float(input("Enter Perc -")) studrecs = pickle.load(fin)
str=input("Enter stream -") studrecs.pop(pos-1)
newdets=[rno,name,perc,str] fin.seek(0)
fin = open("stud.dat","rb+") pickle.dump(studrecs,fin)
pos = int(input(Enter record no to add)) except EOFError:
try: fin.close()
studrecs = pickle.load(fin)
studrecs.insert(pos-1,newdets)
fin.seek(0)
pickle.dump(studrecs,fin)
except EOFError:
fin.close()
Binary File Manipulation (nested List)
def deleterno(): def deletenm():
drno=int(input("\nEnter rno to delete -")) dnm=input("\nEnter name to delete -"))
fin = open("stud.dat","rb+") fin = open("stud.dat","rb+")
ctr,found = 0,”n” ctr,found = 0,”n”
try: try:
studrecs = pickle.load(fin) studrecs = pickle.load(fin)
for r in studrecs: for r in studrecs:
ctr+=1 ctr+=1
if r[0] == drno: if r[1] == dnm:
studrecs.pop(ctr-1) studrecs.pop(ctr-1)
found = “y” found = “y”
break if found ==“y”:
if found ==“y”: fin.seek(0)
fin.seek(0) pickle.dump(studrecs,fin)
pickle.dump(studrecs,fin) except EOFError:
except EOFError: fin.close()
fin.close()
Binary File Manipulation (nested List)
while True:
ch = int(input("\n1. create studen File\n2. show all records\n\
3. Count total records\n4.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\nEnter your choice- "))
if ch==1: elif ch==7:
create() countstream()
elif ch==2: elif ch==8:
display() updaterno()
elif ch==3: elif ch==9:
countall() insertnth()
elif ch==4: elif ch==10:
dispcountperc() deletenth()
elif ch==5: else:
searchrno() print("wrong choice")
elif ch==6: ans=input("\n want to continue ")
searchname() if ans in("n","N"):
break
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
Binary File Manipulation (Dictionary)
def searcheno():
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)
break
else:
print("No such Record Found")
except EOFError:
pass
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 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 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")
tempfile = open("temp.dat","wb")
found="n"
Seno = int(input("Enter Employee no to Edit - "))
try:
while True:
Emp = pickle.load(file)
if Emp["Eno"] == Seno:
eno = Emp["Eno"]
Name = input(" Edited Name :")
Sal = float(input(" Edited Salary:"))
Dept = input("Edited Department :")
Empnew={"Eno":eno,"Name":Name,"Sal":Sal,"Dept":Dept}
found = "y" if found=="n":
pickle.dump(Empnew,tempfile) print("No such record")
else: remove('temp.dat')
pickle.dump(Emp,tempfile) else:
except EOFError: remove('emp.dat')
file.close() rename('temp.dat','emp.dat')
tempfile.close()
Binary File Manipulation (Dictionary)
def EditOnrecno():
file = open("emp.dat","rb")
tempfile = open("temp.dat","wb")
found, ctr = "n",0
Srec = int(input("Enter Record no to Edit - "))
try:
while True:
Emp = pickle.load(file)
ctr +=1
if ctr == Srec:
eno = Emp["Eno"]
Name = input(" Edited Name :")
Sal = float(input(" Edited Salary:"))
Dept = input("Edited Department :")
Empnew={"Eno":eno,"Name":Name,"Sal":Sal,"Dept":Dept}
found = "y"
pickle.dump(Empnew,tempfile) if found=="n":
else: print("No such record")
pickle.dump(Emp,tempfile) remove('temp.dat')
except EOFError: else:
file.close() remove('emp.dat')
tempfile.close() rename('temp.dat','emp.dat')
Binary File Manipulation (Dictionary)
def EditOndept():
file = open("emp.dat","rb")
tempfile = open("temp.dat","wb")
found = "n"
Sdept = input("Enter department name to Edit - ")
try:
while True:
Emp = pickle.load(file)
if Emp["Dept"]== Sdept:
Eno = Emp["Eno"]
Name = input(" Edited Name :")
Sal = float(input(" Edited Salary:"))
Dept = Emp[“Dept”]
Empnew={"Eno":Eno,"Name":Name,"Sal":Sal,"Dept":Dept}
found = "y"
pickle.dump(Empnew,tempfile) if found=="n":
else: print("No such record")
pickle.dump(Emp,tempfile) remove('temp.dat')
except EOFError: else:
file.close() remove('emp.dat')
tempfile.close() rename('temp.dat','emp.dat')
Binary File Manipulation (Dictionary)
while True:
CH = input("1. Create\n2. Display\n3. Search On Emp no\n4.\ Search On Emp name\n5. Count\
records of a given\ Department\n\6. Modify On Emp no\n7. Display Highest\ salary\n 8.Quit\n\
Enter\ your Choice(1-8)")
if CH=='1':
Create()
elif CH=='2':
Disp()
elif CH=='3':
searcheno()
elif CH=='4':
searchenm()
elif CH=='5':
CountDept()
elif CH=='6':
EditOnEmpno()
elif CH=='7':
highestsal()
else:
break
Assessment
import pickle
def create():
f1 = open("emp.dat","wb")
rec = {}
while True:
eno = int(input("Enter Emp no "))
name = input("Enter Name ")
sal = float(input("Enter Salary "))
rec[eno] = [name,sal]
ans = input("Continue")
if ans in "Nn":
break
pickle.dump(rec,f1)
f1.close()
Assessment
def show():
f1 = open("emp.dat","rb")
ctr = 0
try:
rec = pickle.load(f1)

except EOFError:
f1.close()

for keno in rec:


print(keno,rec[keno])
Assessment
def countrec():
f1 = open("emp.dat","rb")
ctr = 0
try:
rec = pickle.load(f1)

except EOFError:
f1.close()
print("Total no of records",len(rec))
Assessment
def srcheno():
seno = int(input("Employee no to search - "))
f1 = open("emp.dat","rb")

try:
rec = pickle.load(f1)

except EOFError:
f1.close()

for keno in rec:


if keno == seno:
print(keno,rec[keno])
break
else:
print("No such record")
Assessment
def srchenm():
senm = input("Employee name to search - ")
f1 = open("emp.dat","rb")
ctr = 0
try:
rec = pickle.load(f1)

except EOFError:
f1.close()
for keno in rec:
if rec[keno][0] == senm:
print(keno,rec[keno])
ctr += 1
if ctr == 0:
print("No such record")
Assessment
def countsal():
ssal = input("Employee salary - ")
f1 = open("emp.dat","rb")
ctr = 0
try:
rec = pickle.load(f1)

except EOFError:
f1.close()
for keno in rec:
if rec[keno][1] >= ssal:
ctr += 1
if ctr == 0:
print("No such record")
else:
print("No. of Emplyees earning salary >",ssal," = ",ctr)
Assessment
def editrecno():
n=int(input("Enter rec no"))
f1=open("emp.dat","rb+")
ctr=0
try:
rec=pickle.load(f1)
except EOFError:
pass
for k in rec:
ctr+=1
if ctr==n:
rec[k][0]=input("Enter name")
rec[k][1]=float(input("Enter salary"))
break
f1.seek(0)
pickle.dump(rec,f1)
f1.close()
Assessment
def editempno():
seno = int(input("Enter emp no"))
f1 = open("emp.dat","rb+")
found=0
try:
rec = pickle.load(f1)
except EOFError:
pass
for k in rec:
if k == seno:
rec[k][0]=input("Enter name")
rec[k][1]=float(input("Enter salary"))
found=1
break
if found==1:
f1.seek(0)
pickle.dump(rec,f1)
else :
print(“record not found”)
f1.close()
Assessment
def insertrecno():
n=int(input("Enter rec no"))
f1=open("emp.dat","rb")
ctr=0
try:
rec = pickle.load(f1)
except EOFError:
f1.close()
newrec = {}
for k in rec:
ctr+=1
if ctr == n:
eno = int(input("Enter Emp no "))
name = input("Enter Name ")
sal = float(input("Enter Salary "))
newrec[eno] = [name,sal]
newrec[k] = rec[k]

f1 = open("emp.dat","wb")
pickle.dump(newrec,f1)
f1.close()
def inserteno():
Assessment
seno = int(input("Enter empno"))
f1=open("emp.dat","rb")
try:
rec = pickle.load(f1)
except EOFError:
f1.close()
eno = list(rec)
found = 0
newrec = {}
for k in rec:
if k == seno:
eno = int(input("Enter Emp no "))
name = input("Enter Name ")
sal = float(input("Enter Salary "))
newrec[eno] = [name,sal]
found = 1
newrec[k] = rec[k]

if found == 1:
f1 = open("emp.dat","wb")
pickle.dump(newrec,f1)
else:
print("No such record found")
f1.close()
Assessment
def deleno():
seno = int(input("Enter empno to delete"))
f1=open("emp.dat","rb")
found = 0
try:
rec = pickle.load(f1)
except EOFError:
f1.close()
for k in rec:
if k == seno:
rec.pop(seno)
found = 1
break
if found == 1:
f1 = open("emp.dat","wb")
pickle.dump(rec,f1)
else:
print("No such record found")
f1.close()
def delrno():
Assessment
srno = int(input("Enter recno to delete"))
f1=open("emp.dat","rb")
found = 0
ctr = 0
try:
rec = pickle.load(f1)
except EOFError:
f1.close()
for k in rec:
ctr+=1
if ctr == srno:
rec.pop(k)
found = 1
break

if found == 1:
f1 = open("emp.dat","wb")
pickle.dump(rec,f1)
else:
print("No such record found")
f1.close()
Assessment
while True:
CH = input("1. Create\n2. Display\n3. Count all records\n4.Search On Emp
no\n5. Search On Emp name\n6. Count all records for salary more\ than user
salary\n7. Edit based on user recordno\n 8.Edit based on user empno \n9.Insert
on user recno\n 10.Insert based on user empno\n\ 11.Delete based on user
empno\n 12.Delete based on user record no\nEnter your Choice(1-8)")
if CH=='1’:
create()
elif CH=='2':
show()
elif CH=='3':
countrec()
elif CH=='4':
srcheno()
elif CH=='5':
srchenm()
Assessment
elif CH=='6':
countsal()
elif CH=='7':
editrecno()
elif CH=='8':
editempno()
elif CH=='9':
insertrecno()
elif CH=='10':
inserteno()
elif CH=='11':
deleno()
elif CH=='12':
delrno()
else:
break
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