FILE HANDLING
26. Write a menu driven program which will create a binary file with name and roll
number. Search for a given roll number and display the name, if not found display
appropriate message.
Code:-
import pickle
def set_data():
rollno = int(input('Enter roll number: '))
name = input('Enter name: ')
print()
#create a dictionary
student = {}
student['rollno'] = rollno
student['name'] = name
return student
def display_data(student):
print('Roll number:', student['rollno'])
print('Name:', student['name'])
print()
def write_record():
#open file in binary mode for writing.
outfile = open('student.dat', 'ab')
#serialize the object and writing to file
pickle.dump(set_data(), outfile)
#close the file
outfile.close()
def read_records():
#open file in binary mode for reading
infile = open('student.dat', 'rb')
#read to the end of file.
while True:
try:
#reading the oject from file
student = pickle.load(infile)
#display the object
display_data(student)
except EOFError:
break
#close the file
infile.close()
def search_record():
infile = open('student.dat', 'rb')
rollno = int(input('Enter rollno to search: '))
flag = False
#read to the end of file.
while True:
try:
#reading the oject from file
student = pickle.load(infile)
#display record if found and set flag
if student['rollno'] == rollno:
display_data(student)
flag = True
break
except EOFError:
break
if flag == False:
print('Record not Found')
print()
#close the file
infile.close()
def show_choices():
print('Menu')
print('1. Add Record')
print('2. Display Records')
print('3. Search a Record')
print('4. Exit')
def main():
while(True):
show_choices()
choice = input('Enter choice(1-4): ')
print()
if choice == '1':
write_record()
elif choice == '2':
read_records()
elif choice == '3':
search_record()
elif choice == '4':
break
else:
print('Invalid input')
#call the main function.
main()
Sample Output:-
27. Write a program which will create a binary file with roll number, name and
marks. Input a roll number and update the marks.
Code:-
# Create a binary file with name, rollno and marks.
#Input a roll no and update the marks.
f=open('student','w+b')
n=int(input('Enter number of students:'))
for i in range(n):
rollno=input('Enter rollno:')
name=input('Enter name of student:')
marks=input('Enter marks:')
brollno=bytes(rollno,encoding='utf-8')
bname=bytes(name,encoding='utf-8')
bmarks=bytes(marks,encoding='utf-8')
f.write(brollno)
f.write(bname)
f.write(bmarks)
f.write(b'\n')
f.seek(0)
data=f.read()
f.seek(0)
sk=input('Enter the roll no whose marks need updatation :')
bsk=bytes(sk,encoding='utf-8')
l=len(bsk)
loc=data.find(bsk)
if loc<0:
print('Details not present')
else:
f.seek(loc+l,0)
i=0
while f.read(1).isalpha():
i=i+1
f.seek(-1,1)
marksu=input('Enter updated marks:')
bmarksu=bytes(marksu,encoding='utf-8')
f.write(bmarksu)
print("Entire content of file after updation is :")
f.seek(0)
udata=f.read()
print(udata.decode())
Sample Output:-