Binary Files
Binary Files
Example 1:
f = open("teams.dat", "rb")
This statement opens the binary file in read mode.
Example 2:
f = open("teams.dat", "wb")
This statement opens the binary file in write mode.
Example 3:
f = open("teams.dat", "ab")
This statement opens the binary file in append mode.
f.close()
f=open("abc","wb")
l=[10,20,30]
a=bytes(l)
f.write(a)
f.close()
f=open("abc","rb")
print(list(f.read()))
f.close()
PICKLE MODULE
“Pickling” is the process in which a Python object is converted into a byte stream,
and “unpickling” is the inverse operation, whereby a byte stream is converted
back into an object.
import pickle
f = open("abc.data","wb")
L = [10,20,30]
pickle.dump(L,f)
f.close()
f = open("abc.data","rb")
y= pickle.load(f)
print(y)
f.close()
f.close()
#STEP-2 Search for a given roll number & display the name
f=open("students.dat","rb")
rno=int(input("enter roll number to search"))
found=False
try:
while True:
rec = pickle.load(f)
if rec[0]==rno:
print("Roll No.",item[0],"Name:",item[1])
found=True
break
except:
f.close()
if not found:
print(rno,"not found in file")
import pickle
def CreateFile():
f=open("Book.dat","ab")
BookNo=int(input("Enter Book No:"))
Book_Name=input("Enter Book Name:")
Author=input("Enter Author Name:")
Price=float(input("Enter Price:"))
rec=[BookNo, Book_Name, Author, Price]
pickle.dump(rec,f)
f.close()
def CountRec(Author):
f=open("Book.dat","rb")
count=0
try:
while True:
rec=pickle.load(f)
if rec[2]==Author:
count+=1
except:
f.close()
return count
UPDATE OPERATION ON A BINARY FILE
Algorithm
1.Read the data to be update bookno,price
2. Read data from file rec by rec and append to List
update price of rec containing book no
3.Open file write mode and write the above list into
file.
4.Read and display file contents
Program
#2. Read data from file rec by rec and append to List
# update price of rec containing book no
f=open("Book.dat","rb")
L=[]
import pickle
try:
while True:
rec=pickle.load(f)
if rec[0]==bookno:
rec[3]=price
L.append(rec)
except:
f.close()
print(L)
#3.Open file write mode and write the above list into
file.
f=open("Book.dat","wb")
for x in L:
pickle.dump(x,f)
f.close()