Binary File Class 12
Binary File Class 12
def insert_rec():
f = open("sales.dat","ab")
c = 'yes'
while True:
sales_id=int(input("Enter ID:"))
name=input("Enter Name:")
city=input("Enter City:")
d = {"SalesId":sales_id,"Name":name,"City":city}
pickle.dump(d,f)
print("Record Inserted.")
print("Want to insert more records, Type yes:")
c = input()
c = c.lower()
if c not in 'yes':
break
main_menu()
f.close()
def display_rec():
f = open("sales.dat","rb")
try:
while True:
d = pickle.load(f)
print(d)
except Exception:
f.close()
main_menu()
def search_rec():
f = open("sales.dat","rb")
s=int(input("Enter id to search:"))
f1 = 0
try:
while True:
d = pickle.load(f)
if d["SalesId"]==s:
f1=1
print(d)
break
except Exception:
f.close()
if f1==0:
print("Record not found...")
else:
print("Record found...")
main_menu()
def update_rec():
f1 = open("sales.dat","rb")
f2 = open("temp.dat","wb")
s=int(input("Enter id to update:"))
try:
while True:
d = pickle.load(f1)
if d["SalesId"]==s:
d["Name"]=input("Enter Name:")
d["City"]=input("Enter City:")
pickle.dump(d,f2)
except EOFError:
print("Record Updated.")
f1.close()
f2.close()
main_menu()
def delete_rec():
f1 = open("sales.dat","rb")
s=int(input("Enter id to delete:"))
try:
while True:
d = pickle.load(f1)
if s in d:
del d[s]
pickle.dump(d,f1)
except EOFError:
print("Record Deleted.")
f1.close()
main_menu()
Search records with relational operator
[5] Write a function to write data into binary file marks.dat and display the records of students
who scored more than 95 marks.
import pickle
def search_95plus():
f = open("marks.dat","ab")
while True:
rn=int(input("Enter the rollno:"))
sname=input("Enter the name:")
marks=int(input("Enter the marks:"))
rec=[]
data=[rn,sname,marks]
rec.append(data)
pickle.dump(rec,f)
ch=input("Wnat more records?Yes:")
if ch.lower() not in 'yes':
break
f.close()
f = open("marks.dat","rb")
cnt=0
try:
while True:
data = pickle.load(f)
for s in data:
if s[2]>95:
cnt+=1
print("Record:",cnt)
print("RollNO:",s[0])
print("Name:",s[1])
print("Marks:",s[2])
except Exception:
f.close()
search_95plus()
[6] Write a function to count records from the binary file marks.dat.
import pickle
def count_records():
f = open("marks.dat","rb")
cnt=0
try:
while True:
data = pickle.load(f)
for s in data:
cnt+=1
except Exception:
f.close()
print("The file has ", cnt, " records.")
count_records()