-
Notifications
You must be signed in to change notification settings - Fork 12.9k
Expand file tree
/
Copy pathFile handle binary read (record in non list form).py
More file actions
47 lines (39 loc) · 1.63 KB
/
File handle binary read (record in non list form).py
File metadata and controls
47 lines (39 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import os
import pickle
from typing import List, Tuple
def read_binary_file() -> None:
"""
Read student records from a binary file.
Automatically creates the file with empty records if it doesn't exist.
Raises:
pickle.UnpicklingError: If file content is corrupted.
PermissionError: If unable to create or read the file.
"""
file_path = r"1 File handle\File handle binary\studrec.dat"
# Ensure directory exists
directory = os.path.dirname(file_path)
if not os.path.exists(directory):
os.makedirs(directory, exist_ok=True)
print(f"Created directory: {directory}")
# Create empty file if it doesn't exist
if not os.path.exists(file_path):
with open(file_path, "wb") as file:
pickle.dump([], file) # Initialize with empty list
print(f"Created new file: {file_path}")
try:
# Read student records
with open(file_path, "rb") as file:
student_records: List[Tuple[int, str, float]] = pickle.load(file)
# Print records in a formatted table
print("\nStudent Records:")
print(f"{'ROLL':<10}{'NAME':<20}{'MARK':<10}")
print("-" * 40)
for record in student_records:
roll, name, mark = record
print(f"{roll:<10}{name:<20}{mark:<10.1f}")
except pickle.UnpicklingError:
print(f"ERROR: File {file_path} is corrupted.")
except Exception as e:
print(f"ERROR: Unexpected error - {str(e)}")
if __name__ == "__main__":
read_binary_file()