Binary files notes2
Binary files notes2
BINARY FILES:
A Binary file stores the information in the form of a
stream of bytes.
module.
import pickle
Syntax: pickle.dump(<structure>,<FileObject>)
Here, Structure can be list or dictionary. File Object is the file handle
of file in which we have to write.
import pickle
f=open("bina.dat","wb")
l=['Ram',99,'city']
pickle.dump(l,f)
f.close()
pickle.load() – This method is used to read data from a file and return
back into the structure (list/dictionary).
import pickle
f=open("my_bin1.bin","wb")
D1={3:'Maruti',2:'Honda',4:'Hundai',1:'BMW'}
pickle.dump(D1,f)
f.close()
f1=open("my_bin1.bin","rb")
D2=pickle.load(f1)
print(D2)
f.close()
Note:
The pickle.load() function would raise EOFError( a run time
exception) when you reach EOF while reading from the file .You can
handle this by following one of the below given two methods
1. Using try and except blocks
2. Using with statement
import pickle
stu={ }
f=open('s.dat','wb')
while True:
roll=int(input("Enter Roll Number: "))
name=input("Enter Name: ")
marks=float(input("Enter Marks: "))
stu['Roll_no']=roll
stu['Name']=name
stu['Marks']=marks
pickle.dump(stu,f)
ch =input("Do you want to add more record?(y/n): ")
if ch.lower()=='n':
break
print("Student records added successfully.")
f.close()
Program to open file s.dat created above, reading the objects written
in it and display them.
import pickle
f=open('s.dat','rb')
try:
while True:
data=pickle.load(f)
print(data)
except EOFError:
pass
f.close()
Create a binary file of student with roll number, name and marks.
Search for a particular record, update the student record
import pickle
def Write():
f=open("stu.dat","wb")
d={}
while True:
rno = int(input("Enter student RollNo:"))
nam = input("Enter student Name :")
marks=int(input("Enter student marks:"))
d['Roll_No.']=rno
d['Name']=nam
d['Marks']=marks
pickle.dump(d,f)
ch=input("Want to add more record?(y/n):")
if ch.lower()=='n':
break
f.close()
def Read():
f=open("stu.dat","rb")
try:
while True:
data=pickle.load(f)
print(data)
except:
f.close()
def Search():
f=open('stu.dat','rb')
rno = int(input("Enter rollno.to be search: "))
found=0
try:
while True:
data=pickle.load(f)
if data['Roll_No.']==rno:
print(data)
found=1
break
except EOFError:
f.close()
if found==0:
print("No record found")
def Update():
f=open('stu.dat','rb+')
rno=int(input("Enter rollno to be updated:"))
found=0
try:
while True:
pos = f.tell() # Store the current position
data = pickle.load(f)
if data['Roll_No.'] == rno:
data['Marks'] = int(input("Enter updated marks: "))
f.seek(pos) # Move the file pointer back to the start of the
record
pickle.dump(data, f) # Update the record
found = 1
break # Exit after updating the record
except EOFError:
pass # Reached the end of the file
f.close()
if found == 0:
print("No record found")
Write()
Read()
Search()
Update()
Read()
Output: