Practical_Program_4_-_Binary_File_Handling_2[1]
Practical_Program_4_-_Binary_File_Handling_2[1]
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')
def read_records():
#open file in binary mode for reading
infile = open('student.dat', 'rb')
def search_record():
infile = open('student.dat', 'rb')
rollno = int(input('Enter rollno to search: '))
flag = False
except EOFError:
break
if flag == False:
print('Record not Found')
print()
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()
else:
print('Invalid input')
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:-
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:-