0% found this document useful (0 votes)
9 views2 pages

Ques 1

QUESTION FOR CLASS 12 CS

Uploaded by

wa298825
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views2 pages

Ques 1

QUESTION FOR CLASS 12 CS

Uploaded by

wa298825
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

import pickle

# File path for the binary file


file_path = 'students.dat'

# Function to create a binary file with initial data


def create_binary_file():
students = [
{'roll_no': 1, 'name': 'Alice', 'marks': 85},
{'roll_no': 2, 'name': 'Bob', 'marks': 78},
{'roll_no': 3, 'name': 'Charlie', 'marks': 92},
]
with open(file_path, 'wb') as file:
pickle.dump(students, file)
print("Binary file created with initial data.")

# Function to display the contents of the binary file


def display_file_contents():
try:
with open(file_path, 'rb') as file:
students = pickle.load(file)
for student in students:
print(student)
except Exception as e:
print(f"Error reading file: {e}")

# Function to update marks for a given Roll No


def update_marks():
try:
roll_no = int(input("Enter the Roll No to update marks: "))
new_marks = int(input("Enter the new marks: "))

with open(file_path, 'rb') as file:


students = pickle.load(file)

# Update the marks


for student in students:
if student['roll_no'] == roll_no:
student['marks'] = new_marks
print(f"Marks updated for Roll No {roll_no}: {student}")
break
else:
print(f"No student found with Roll No {roll_no}.")

# Write updated data back to the binary file


with open(file_path, 'wb') as file:
pickle.dump(students, file)
except Exception as e:
print(f"Error: {e}")

# Main program
if _name_ == "_main_":
create_binary_file()
print("\nInitial File Contents:")
display_file_contents()

print("\nUpdating Marks:")
update_marks()
print("\nUpdated File Contents:")
display_file_contents()

You might also like