0% found this document useful (0 votes)
13 views

Binary File Exercise

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)
13 views

Binary File Exercise

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/ 5

Binary File Exercise

#Write a program to read and write programming


languages
#stored in the tuple to binary file PL.dat.
import pickle
def bin2tup():
f = open("PL.dat","wb")
t = ('C','C++','Java','Python')
pickle.dump(t,f)
f.close()
f = open("PL.dat","rb")
d = pickle.load(f)
print("PL1:",d[0])
print("PL2:",d[1])
print("PL3:",d[2])
print("PL4:",d[3])
f.close()
bin2tup()

'''Write a program to store customer data into a binary


file cust.dat using a dictionary and print them on screen
after reading them. The customer data contains ID as
key, and name, city as values.'''
import pickle
def bin2dict():
f = open("cust.dat","wb")
d = {'C0001':['Subham','Ahmedabad'],
'C0002':['Bhavin','Anand'],
'C0003':['Chintu','Baroda']}
pickle.dump(d,f)
f.close()
f = open("cust.dat","rb")
d = pickle.load(f)
print(d)
f.close()
bin2dict()

''' 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("Want 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()

Count All Record from file


import pickle
def count_records():
f = open("marks.dat","rb")
cnt=0
try:
while True:
data = pickle.load(f)
print(data)
cnt+=1
except Exception:
f.close()
print("The file has ", cnt, " records.")
count_records()

''' Write a program to know the cursor position and


print the text according to below-given specifications:
Print the initial position Move the cursor to 4th position
Display next 5 characters Move the cursor to the next
10 charactersPrint the current cursor position Print next
10 characters from the current cursor position'''
def program9():
f = open("ankita.txt","r")
print(f.tell())
print(f.read(4))
f.seek(4,0)
print(f.read(5))
f.seek(10,0)
print(f.tell())
print(f.seek(7,0))
print(f.read(10))
program9()

You might also like