0% found this document useful (0 votes)
23 views25 pages

Binary File Handling in Python-2023

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views25 pages

Binary File Handling in Python-2023

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

BINARY FILES

• Binary files the data is stored in the same manner as it is stored


in memory.

• Binary files are not human readable. When opened using any
text editor, the data is unrecognizable.

• They can be anything from image files to pdf files


In Text files, everything that you read or write is in the form
of strings.

• Python allows you to define several types of data structures, E.g.


such as lists, dictionaries, custom objects, etc. a =["Rohan", "XI-A", 90.5]
• To store data in a text file, you will have to think about how to b =["Radha", "XI-B", 89.5]
transform the object (list, dictionary etc.) into a series of f=open("student.txt","w")
strings and use the opposite operation to recover the variable. s=""
• However, this is very cumbersome, also it is very susceptible to for i in a:
small changes. s=s+ str(i)+", "

Fortunately, Python comes with a module that allows us to save s=s+"\n"


almost everything we want, called Pickle. f.write(s)
import pickle s=""
for i in b:
a =["Rohan", "XI-A", 90.5] s=s+ str(i)+", "
b =["Radha", "XI-B", 89.5] s=s+"\n"
f=open("student.txt","wb") f.write(s)
pickle.dump(a,f) f.close()
pickle.dump(b,f)

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

DATA IS WRITTEN AS MULTIPLE RECORDS DATA IS WRITTEN AS SINGLE RECORD

Binary file is opened Binary file is opened

Data is accepted in the Data is accepted, added


form of records and to one variable(list) and
written into the file one then one record is added
by one to the file

After all records have


After all records have
been written, file is
been written, file is
closed
closed
f=open("student","wb")
f=open("student","wb") n=int(input("How many students"))
n=int(input("How many students")) t=[]
for i in range(n): for i in range(n):
s_rec=eval(input("Enter name, class, percentage")) s_rec=eval(input("Enter name, class, percentage"))
pickle.dump(s_rec, f) t.append(s_rec)

f.close() pickle.dump(t, f)
READING FROM A BINARY FILE
2 Approaches

DATA IS WRITTEN AS MULTIPLE RECORDS DATA IS WRITTEN AS SINGLE RECORD


Binary file is opened
Binary file is opened
Handle exception
Read records one by one Data is read using a
in a loop single load() statement

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”]

[“ravi”, 34, “Manager”] [“aarush”, 45, “Sr. Manager”] [“usha”,56,”clerk”]


APPENDING IN A BINARY FILE
(data stored as single record)
CAN BE LEFT FOR THE MID SEM
def append():
f=open("employee","rb+")
t_rec=pickle.load(f)
x=eval(input("Enter name, age, designation to be appended: "))
t_rec.append(x)
f.seek(0)
pickle.dump(t_rec, f)
f.close()
DELETING IN A BINARY FILE
(data stored as single record)
CAN BE LEFT FOR THE MID SEM
import os
def remove_rec():
f=open("employee","rb")
g=open("temp","wb")
o_rec=pickle.load(f) Read entire data
n_rec=[]

a=input("Enter name of employee to be deleted")


for i in o_rec:

if i[0]!=a: Create a new record with all data


n_rec.append(i) except the one to be deleted

pickle.dump(n_rec, g) Dump the new record


f.close()
g.close()
os.remove("employee")
os.rename("temp","employee")
DELETING IN A BINARY FILE
(data stored as multiple records)
def remove_rec():
f=open("employee","rb")
g=open("temp","wb")

a=input("Enter name of employee to be deleted")


while True: # check for end of file
try:
o_rec=pickle.load(f) Read one record at a time
if o_rec[0]!=a:
pickle.dump(o_rec,g) Dump the record if it is to be retained
except EOFError:
break

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=[]

a=input("Enter name of employee whose designation is to be modified")


for i in o_rec:
if i[0]==a: Make changes to the record being
i[2]=input("Enter new designation") modified and then dump it
n_rec.append(i)
else:
n_rec.append(i) Dump the records directly that are not to
be modified
pickle.dump(n_rec,g)
f.close()
g.close()
os.remove("employee")
os.rename("temp","employee")
def update_rec(): UPDATING IN A BINARY FILE
f=open("employee","rb") (data stored as multiple records)
g=open("temp","wb")

a=input("Enter name of employee to be modified: ")


while True: # check for end of file
try:
o_rec=pickle.load(f) Read one record at a time
if o_rec[0]==a:
o_rec[2]=input("Enter new designation") Make changes if needed
pickle.dump(o_rec,g) and then dump it

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):

n=int(input("How many records do you want to enter: "))


f=open(nm,"wb")
for i in range(n):
d={}
country=input("Enter country name ")
capital=input("Enter capital of “ + country)
d[country]=capital
pickle.dump(d,f)
f.close()
QUESTIONS (Theory)

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

while True: # check for end of file


try:
o_rec=pickle.load(f)
if o_rec[1]==_________:

pickle.dump(_____)

except EOFError:
break
____
______

You might also like