importstruct
defcreate_binary_file_with_marks(filename):
data = [(1, "Alice",
85), (2, "Bob", 90), (3, "Charlie", 78)]
with open(filename, 'wb') as
file:
forroll_number, name, marks in
data:
file.write(struct.pack('I20sI',
roll_number, name.encode(), marks))
defupdate_marks_in_binary_file(filename,
roll_number, new_marks):
with open(filename, 'r+b') as
file:
while True:
try:
roll_number_bytes, name_bytes,
marks_bytes = struct.unpack('I20sI', file.read(28))
ifroll_number ==
struct.unpack('I', roll_number_bytes)[0]:
file.seek(-4, 1) # Move back 4 bytes to overwrite marks
file.write(struct.pack('I',
new_marks))
print("Marks updated
successfully.")
return
exceptstruct.error:
print("Roll number not
found.")
return
if __name__ ==
"__main__":
filename =
"students_marks.bin"
create_binary_file_with_marks(filename)
roll_number_to_update =
int(input("Enter roll number to update: "))
new_marks = int(input("Enter
new marks: "))
update_marks_in_binary_file(filename,
roll_number_to_update, new_marks)
No comments:
Post a Comment