Skip to content

Commit 7b09272

Browse files
committed
fix bugs and update for requerments and python 3.13.5 grammars
1 parent 20aa30f commit 7b09272

34 files changed

+1628
-1676
lines changed
Lines changed: 48 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,51 @@
11
import pickle
2+
from typing import List, Tuple
23

3-
def bdelete():
4-
# Opening a file & loading it
5-
with open("studrec.dat","rb") as F:
6-
stud = pickle.load(F)
7-
print(stud)
4+
def delete_student_record() -> None:
5+
"""
6+
Delete a student record from the binary data file 'studrec.dat' based on the provided roll number.
7+
8+
This function performs the following operations:
9+
1. Reads the current student records from 'studrec.dat'
10+
2. Prompts the user to enter a roll number to delete
11+
3. Removes the record with the specified roll number
12+
4. Writes the updated records back to 'studrec.dat'
13+
14+
Each student record is stored as a tuple in the format: (roll_number, ...)
15+
16+
Raises:
17+
FileNotFoundError: If 'studrec.dat' does not exist.
18+
pickle.UnpicklingError: If the file contains corrupted data.
19+
ValueError: If the user input cannot be converted to an integer.
20+
"""
21+
try:
22+
# Read existing student records from file
23+
with open("studrec.dat", "rb") as file:
24+
student_records: List[Tuple[int, ...]] = pickle.load(file)
25+
print("Current student records:", student_records)
26+
27+
# Get roll number to delete
28+
roll_number: int = int(input("Enter the roll number to delete: "))
29+
30+
# Filter out the record with the specified roll number
31+
updated_records: List[Tuple[int, ...]] = [
32+
record for record in student_records if record[0] != roll_number
33+
]
34+
35+
# Write updated records back to file
36+
with open("studrec.dat", "wb") as file:
37+
pickle.dump(updated_records, file)
38+
39+
print(f"Record with roll number {roll_number} has been deleted.")
40+
41+
except FileNotFoundError:
42+
print("Error: The file 'studrec.dat' does not exist.")
43+
except pickle.UnpicklingError:
44+
print("Error: The file contains corrupted data.")
45+
except ValueError as e:
46+
print(f"Error: Invalid input. Please enter an integer. {e}")
47+
except Exception as e:
48+
print(f"An unexpected error occurred: {e}")
849

9-
# Deleting the Roll no. entered by user
10-
rno = int(input("Enter the Roll no. to be deleted: "))
11-
with open("studrec.dat","wb") as F:
12-
rec = [i for i in stud if i[0] != rno]
13-
pickle.dump(rec, F)
14-
15-
16-
bdelete()
50+
if __name__ == "__main__":
51+
delete_student_record()
Lines changed: 46 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,47 @@
1+
import os
12
import pickle
2-
3-
4-
def binary_read():
5-
with open("studrec.dat","rb") as b:
6-
stud = pickle.load(b)
7-
print(stud)
8-
9-
# prints the whole record in nested list format
10-
print("contents of binary file")
11-
12-
for ch in stud:
13-
14-
print(ch) # prints one of the chosen rec in list
15-
16-
rno = ch[0]
17-
rname = ch[1] # due to unpacking the val not printed in list format
18-
rmark = ch[2]
19-
20-
print(rno, rname, rmark, end="\t")
21-
22-
23-
binary_read()
3+
from typing import List, Tuple
4+
5+
def read_binary_file() -> None:
6+
"""
7+
Read student records from a binary file.
8+
Automatically creates the file with empty records if it doesn't exist.
9+
10+
Raises:
11+
pickle.UnpicklingError: If file content is corrupted.
12+
PermissionError: If unable to create or read the file.
13+
"""
14+
file_path = r"1 File handle\File handle binary\studrec.dat"
15+
16+
# Ensure directory exists
17+
directory = os.path.dirname(file_path)
18+
if not os.path.exists(directory):
19+
os.makedirs(directory, exist_ok=True)
20+
print(f"Created directory: {directory}")
21+
22+
# Create empty file if it doesn't exist
23+
if not os.path.exists(file_path):
24+
with open(file_path, "wb") as file:
25+
pickle.dump([], file) # Initialize with empty list
26+
print(f"Created new file: {file_path}")
27+
28+
try:
29+
# Read student records
30+
with open(file_path, "rb") as file:
31+
student_records: List[Tuple[int, str, float]] = pickle.load(file)
32+
33+
# Print records in a formatted table
34+
print("\nStudent Records:")
35+
print(f"{'ROLL':<10}{'NAME':<20}{'MARK':<10}")
36+
print("-" * 40)
37+
for record in student_records:
38+
roll, name, mark = record
39+
print(f"{roll:<10}{name:<20}{mark:<10.1f}")
40+
41+
except pickle.UnpicklingError:
42+
print(f"ERROR: File {file_path} is corrupted.")
43+
except Exception as e:
44+
print(f"ERROR: Unexpected error - {str(e)}")
45+
46+
if __name__ == "__main__":
47+
read_binary_file()
Lines changed: 110 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,115 @@
1-
# Updating records in a binary file
2-
1+
import os
32
import pickle
3+
from typing import List, Tuple
44

5+
def initialize_file_if_not_exists(file_path: str) -> None:
6+
"""
7+
Check if file exists. If not, create it with an empty list of records.
8+
9+
Args:
10+
file_path (str): Path to the file.
11+
12+
Raises:
13+
ValueError: If file_path is empty.
14+
"""
15+
if not file_path:
16+
raise ValueError("File path cannot be empty.")
17+
18+
directory = os.path.dirname(file_path)
19+
if directory and not os.path.exists(directory):
20+
os.makedirs(directory, exist_ok=True)
21+
22+
if not os.path.exists(file_path):
23+
with open(file_path, "wb") as f:
24+
pickle.dump([], f)
25+
print(f"Created new file: {file_path}")
526

6-
def update():
7-
with open("class.dat", "rb+") as F:
8-
S = pickle.load(F)
9-
found = False
10-
rno = int(input("enter the roll number you want to update"))
11-
12-
for i in S:
13-
if rno == i[0]:
14-
print(f"the currrent name is {i[1]}")
15-
i[1] = input("enter the new name")
16-
found = True
17-
break
18-
19-
if found:
20-
print("Record not found")
21-
22-
else:
23-
F.seek(0)
24-
pickle.dump(S, F)
25-
27+
def update_student_record(file_path: str) -> None:
28+
"""
29+
Update a student's name in the binary file by roll number.
30+
31+
Args:
32+
file_path (str): Path to the binary file containing student records.
33+
"""
34+
initialize_file_if_not_exists(file_path)
35+
36+
try:
37+
with open(file_path, "rb+") as f:
38+
# Load existing records
39+
records: List[Tuple[int, str, float]] = pickle.load(f)
40+
41+
if not records:
42+
print("No records found in the file.")
43+
return
44+
45+
# Get roll number to update
46+
roll_to_update = int(input("Enter roll number to update: "))
47+
found = False
48+
49+
# Find and update the record
50+
for i, record in enumerate(records):
51+
if record[0] == roll_to_update:
52+
current_name = record[1]
53+
new_name = input(f"Current name: {current_name}. Enter new name: ").strip()
54+
55+
if new_name:
56+
# Create a new tuple with updated name
57+
updated_record = (record[0], new_name, record[2])
58+
records[i] = updated_record
59+
print("Record updated successfully.")
60+
else:
61+
print("Name cannot be empty. Update cancelled.")
62+
63+
found = True
64+
break
65+
66+
if not found:
67+
print(f"Record with roll number {roll_to_update} not found.")
68+
return
69+
70+
# Rewrite the entire file with updated records
71+
f.seek(0)
72+
pickle.dump(records, f)
73+
f.truncate() # Ensure any remaining data is removed
74+
75+
except ValueError:
76+
print("Error: Invalid roll number. Please enter an integer.")
77+
except pickle.UnpicklingError:
78+
print("Error: File content is corrupted and cannot be read.")
79+
except Exception as e:
80+
print(f"An unexpected error occurred: {str(e)}")
2681

27-
update()
82+
def display_all_records(file_path: str) -> None:
83+
"""
84+
Display all student records in the binary file.
85+
86+
Args:
87+
file_path (str): Path to the binary file.
88+
"""
89+
initialize_file_if_not_exists(file_path)
90+
91+
try:
92+
with open(file_path, "rb") as f:
93+
records: List[Tuple[int, str, float]] = pickle.load(f)
94+
95+
if not records:
96+
print("No records found in the file.")
97+
return
98+
99+
print("\nAll Student Records:")
100+
print(f"{'ROLL':<8}{'NAME':<20}{'PERCENTAGE':<12}")
101+
print("-" * 40)
102+
103+
for record in records:
104+
print(f"{record[0]:<8}{record[1]:<20}{record[2]:<12.1f}")
105+
106+
except pickle.UnpicklingError:
107+
print("Error: File content is corrupted and cannot be read.")
108+
except Exception as e:
109+
print(f"An unexpected error occurred: {str(e)}")
28110

29-
with open("class.dat", "rb") as F:
30-
print(pickle.load(F))
111+
if __name__ == "__main__":
112+
FILE_PATH = r"class.dat" # Update with your actual file path
113+
114+
update_student_record(FILE_PATH)
115+
display_all_records(FILE_PATH)

0 commit comments

Comments
 (0)