Binary File Handling in Python-2023
Binary File Handling in Python-2023
• Binary files are not human readable. When opened using any
text editor, the data is unrecognizable.
f.close()
BINARY FILES
Using pickle module
Python pickle module is used for serializing and de-serializing a Python
object structure. Any object in Python can be pickled so that it can be
saved on disk. What pickle does is that it “serializes” the object first
before writing it to file. Pickling is a way to convert a python
object (list, dict, etc.) into a character or byte stream. The idea
is that this character stream contains all the information necessary to
reconstruct the object in another python script.
• ‘rb’ – reading a binary file. Error message if file does not exist.
• ‘wb’- writing a binary file. New file created if the file does not exist.
• ‘ab’- for appending or adding data to the binary file. File pointer placed at the end of
the file if the file exists, otherwise a new file is created.
• ‘rb+’-opens binary file for reading as well as writing. File pointer at beginning of file
• ‘wb+’-opens binary file for reading as well as writing. If file exists data is truncated. File
pointer at beginning of file
• ‘ab+’- opens binary file for reading as well as writing. File pointer placed at the end fo
the file if the file exists, otherwise a new file is created.
WRITING INTO A BINARY FILE
import pickle
d = {1:"Avinash",2:"charu",3:"Devika"}
f= open("file_bin","wb")
pickle.dump(d, f)
f.close()
READING FROM A BINARY FILE
import pickle
pickle_f = open("file_bin","rb")
e = pickle.load(pickle_f)
print(e)
pickle_f.close()
import pickle
f=open("student","wb")
n=int(input("How many students"))
for i in range(n):
s_rec=eval(input("Enter name, class, percentage"))
pickle.dump(s_rec, f)
f.close()
f=open("student","rb")
t_rec=pickle.load(f)
print(t_rec)
import pickle
f=open("student","wb")
n=int(input("How many students"))
for i in range(n):
s_rec=eval(input("Enter name, class, percentage"))
pickle.dump(s_rec, f) How to read multiple records from a binary
file??
f.close()
An exception is raised when you reach the EOF
and still try to read
f=open("student","rb")
while True:
t_rec=pickle.load(f)
print(t_rec)
import pickle
f=open("student","wb")
n=int(input("How many students"))
for i in range(n):
s_rec=eval(input("Enter name, class, percentage"))
pickle.dump(s_rec, f)
Use any of the two approaches to read
f.close()
multiple records from a binary file
f=open("student","rb") f=open("student","rb")
while True: OR try:
try: while True:
t_rec=pickle.load(f) t_rec=pickle.load(f)
print(t_rec) print(t_rec)
except EOFError: except EOFError:
print('EOF!!!') print('EOF!!!')
f.close() f.close()
break
import pickle
f=open("student","wb")
n=int(input("How many students")) Single record in binary file
t=[]
for i in range(n):
s_rec=eval(input("Enter name, class, percentage"))
t.append(s_rec)
pickle.dump(t, f)
f.close()
f=open("student","rb")
t_rec=pickle.load(f)
print(t_rec)
f.close()
WRITING INTO A BINARY FILE
2 Approaches
f.close() pickle.dump(t, f)
READING FROM A BINARY FILE
2 Approaches
When EOFError
exception is raised, close File is closed
the file and break out of
the loop
f=open("student","rb")
f=open("student","rb") t_rec=pickle.load(f)
while True: # check for end of file print(t_rec)
try: f.close()
t_rec=pickle.load(f)
print(t_rec)
except EOFError:
print('EOF!!!')
f.close()
break
SEARCHING IN A BINARY FILE (done in previous class) (data stored as multiple records)
[“ravi”, 34, “Manager”] [“aarush”, 45, “Sr. Manager”] [“usha”,56,”clerk”]
import pickle
def search_agerange():
def write_rec(): f=open("employee","rb")
f=open("employee","wb") print("SEARCHING CONTENTS OF EMPLOYEE FILE ON BASIS OF AGE")
n=int(input("How many employees")) found=0
for i in range(n): while True:
e_rec=eval(input("Enter name, age, try:
designation")) t_rec=pickle.load(f)
pickle.dump(e_rec, f) if t_rec[1]>=20 and t_rec[1]<=30:
f.close() print(t_rec)
found+=1
def read_rec(): except EOFError:
f=open("employee","rb") f.close()
print("DISPLAYING CONTENTS OF EMPLOYEE FILE") break
while True: if found==0:
try: print("Record not found")
t_rec=pickle.load(f)
print(t_rec)
except EOFError: write_rec()
print('EOF!!!') read_rec()
f.close() search_agerange()
break
SEARCHING IN A BINARY FILE (done in previous class)
(data stored as single record) CAN BE LEFT FOR THE MID SEM
import pickle
def write_rec():
f=open("employee","wb") [ ["Murli",25,"Clerk"], ["Manohar",45,"Manager"] ]
n=int(input("How many employees"))
data=[]
for i in range(n): def search_agerange():
e_rec=eval(input("Enter name, age, designation")) f=open("employee","rb")
data.append(e_rec) print("SEARCHING CONTENTS OF EMPLOYEE FILE ON BASIS OF AG
pickle.dump(data,f) found=0
f.close()
t_rec=pickle.load(f)
def read_rec(): for i in t_rec:
f=open("employee","rb") if i[1]>=20 and i[1]<=30:
print("DISPLAYING CONTENTS OF EMPLOYEE FILE") print(i)
t_rec=pickle.load(f)
for i in t_rec: found=1
print(i) if found==0:
print("Not found")
write_rec()
read_rec()
Search_agerange()
APPENDING IN A BINARY FILE
(data stored as multiple records)
def append():
f=open("employee","ab")
x=eval(input("Enter name, age, designation to be appended: "))
pickle.dump(x, f)
f.close()
New Record
[“priya”, 54, “Directo”]
f.close()
g.close()
os.remove("employee")
os.rename("temp","employee")
UPDATING DATA IN A BINARY FILE
(data stored as single record)
CAN BE LEFT FOR THE MID SEM
def update_rec():
f=open("employee","rb")
g=open("temp","wb")
o_rec=pickle.load(f) Read entire data
n_rec=[]
else:
pickle.dump(o_rec,g)
except EOFError:
break
f.close()
g.close()
os.remove("employee")
os.rename("temp","employee")
QUESTIONS (Theory)
Write a function that takes the name of a file and writes n records in a binary file in the
following format
{“india”:”delhi”}, (“Indonesia”:”Jakarta”}
import pickle
def f(nm):
Write a function that transfers all records with company name “Dell” from binary file “laptop” to another
binary file “specific”
Records are stored one after the other in the following format def copy_rec():
[Model Id, company name, price] f=open(" _____","rb")
g=open("_____","wb")
found=0
pickle.dump(_____)
except EOFError:
break
____
______