Skip to content

Commit e63ebab

Browse files
committed
ruff fromat update
1 parent 1c4be4c commit e63ebab

File tree

439 files changed

+8129
-6460
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

439 files changed

+8129
-6460
lines changed

1 File handle/File handle binary/Deleting record in a binary file.py

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,15 @@
44
def delete_student_record() -> None:
55
"""
66
Delete a student record from the binary data file 'studrec.dat' based on the provided roll number.
7-
7+
88
This function performs the following operations:
99
1. Reads the current student records from 'studrec.dat'
1010
2. Prompts the user to enter a roll number to delete
1111
3. Removes the record with the specified roll number
1212
4. Writes the updated records back to 'studrec.dat'
13-
13+
1414
Each student record is stored as a tuple in the format: (roll_number, ...)
15-
15+
1616
Raises:
1717
FileNotFoundError: If 'studrec.dat' does not exist.
1818
pickle.UnpicklingError: If the file contains corrupted data.
@@ -23,21 +23,21 @@ def delete_student_record() -> None:
2323
with open("studrec.dat", "rb") as file:
2424
student_records: list[tuple[int, ...]] = pickle.load(file)
2525
print("Current student records:", student_records)
26-
26+
2727
# Get roll number to delete
2828
roll_number: int = int(input("Enter the roll number to delete: "))
29-
29+
3030
# Filter out the record with the specified roll number
3131
updated_records: list[tuple[int, ...]] = [
3232
record for record in student_records if record[0] != roll_number
3333
]
34-
34+
3535
# Write updated records back to file
3636
with open("studrec.dat", "wb") as file:
3737
pickle.dump(updated_records, file)
38-
38+
3939
print(f"Record with roll number {roll_number} has been deleted.")
40-
40+
4141
except FileNotFoundError:
4242
print("Error: The file 'studrec.dat' does not exist.")
4343
except pickle.UnpicklingError:
@@ -47,5 +47,6 @@ def delete_student_record() -> None:
4747
except Exception as e:
4848
print(f"An unexpected error occurred: {e}")
4949

50+
5051
if __name__ == "__main__":
51-
delete_student_record()
52+
delete_student_record()

1 File handle/File handle binary/File handle binary read (record in non list form).py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,42 +6,43 @@ def read_binary_file() -> None:
66
"""
77
Read student records from a binary file.
88
Automatically creates the file with empty records if it doesn't exist.
9-
9+
1010
Raises:
1111
pickle.UnpicklingError: If file content is corrupted.
1212
PermissionError: If unable to create or read the file.
1313
"""
1414
file_path = r"1 File handle\File handle binary\studrec.dat"
15-
15+
1616
# Ensure directory exists
1717
directory = os.path.dirname(file_path)
1818
if not os.path.exists(directory):
1919
os.makedirs(directory, exist_ok=True)
2020
print(f"Created directory: {directory}")
21-
21+
2222
# Create empty file if it doesn't exist
2323
if not os.path.exists(file_path):
2424
with open(file_path, "wb") as file:
2525
pickle.dump([], file) # Initialize with empty list
2626
print(f"Created new file: {file_path}")
27-
27+
2828
try:
2929
# Read student records
3030
with open(file_path, "rb") as file:
3131
student_records: list[tuple[int, str, float]] = pickle.load(file)
32-
32+
3333
# Print records in a formatted table
3434
print("\nStudent Records:")
3535
print(f"{'ROLL':<10}{'NAME':<20}{'MARK':<10}")
3636
print("-" * 40)
3737
for record in student_records:
3838
roll, name, mark = record
3939
print(f"{roll:<10}{name:<20}{mark:<10.1f}")
40-
40+
4141
except pickle.UnpicklingError:
4242
print(f"ERROR: File {file_path} is corrupted.")
4343
except Exception as e:
4444
print(f"ERROR: Unexpected error - {str(e)}")
4545

46+
4647
if __name__ == "__main__":
47-
read_binary_file()
48+
read_binary_file()

1 File handle/File handle binary/Update a binary file.py

Lines changed: 28 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -5,111 +5,116 @@
55
def initialize_file_if_not_exists(file_path: str) -> None:
66
"""
77
Check if file exists. If not, create it with an empty list of records.
8-
8+
99
Args:
1010
file_path (str): Path to the file.
11-
11+
1212
Raises:
1313
ValueError: If file_path is empty.
1414
"""
1515
if not file_path:
1616
raise ValueError("File path cannot be empty.")
17-
17+
1818
directory = os.path.dirname(file_path)
1919
if directory and not os.path.exists(directory):
2020
os.makedirs(directory, exist_ok=True)
21-
21+
2222
if not os.path.exists(file_path):
2323
with open(file_path, "wb") as f:
2424
pickle.dump([], f)
2525
print(f"Created new file: {file_path}")
2626

27+
2728
def update_student_record(file_path: str) -> None:
2829
"""
2930
Update a student's name in the binary file by roll number.
30-
31+
3132
Args:
3233
file_path (str): Path to the binary file containing student records.
3334
"""
3435
initialize_file_if_not_exists(file_path)
35-
36+
3637
try:
3738
with open(file_path, "rb+") as f:
3839
# Load existing records
3940
records: list[tuple[int, str, float]] = pickle.load(f)
40-
41+
4142
if not records:
4243
print("No records found in the file.")
4344
return
44-
45+
4546
# Get roll number to update
4647
roll_to_update = int(input("Enter roll number to update: "))
4748
found = False
48-
49+
4950
# Find and update the record
5051
for i, record in enumerate(records):
5152
if record[0] == roll_to_update:
5253
current_name = record[1]
53-
new_name = input(f"Current name: {current_name}. Enter new name: ").strip()
54-
54+
new_name = input(
55+
f"Current name: {current_name}. Enter new name: "
56+
).strip()
57+
5558
if new_name:
5659
# Create a new tuple with updated name
5760
updated_record = (record[0], new_name, record[2])
5861
records[i] = updated_record
5962
print("Record updated successfully.")
6063
else:
6164
print("Name cannot be empty. Update cancelled.")
62-
65+
6366
found = True
6467
break
65-
68+
6669
if not found:
6770
print(f"Record with roll number {roll_to_update} not found.")
6871
return
69-
72+
7073
# Rewrite the entire file with updated records
7174
f.seek(0)
7275
pickle.dump(records, f)
7376
f.truncate() # Ensure any remaining data is removed
74-
77+
7578
except ValueError:
7679
print("Error: Invalid roll number. Please enter an integer.")
7780
except pickle.UnpicklingError:
7881
print("Error: File content is corrupted and cannot be read.")
7982
except Exception as e:
8083
print(f"An unexpected error occurred: {str(e)}")
8184

85+
8286
def display_all_records(file_path: str) -> None:
8387
"""
8488
Display all student records in the binary file.
85-
89+
8690
Args:
8791
file_path (str): Path to the binary file.
8892
"""
8993
initialize_file_if_not_exists(file_path)
90-
94+
9195
try:
9296
with open(file_path, "rb") as f:
9397
records: list[tuple[int, str, float]] = pickle.load(f)
94-
98+
9599
if not records:
96100
print("No records found in the file.")
97101
return
98-
102+
99103
print("\nAll Student Records:")
100104
print(f"{'ROLL':<8}{'NAME':<20}{'PERCENTAGE':<12}")
101105
print("-" * 40)
102-
106+
103107
for record in records:
104108
print(f"{record[0]:<8}{record[1]:<20}{record[2]:<12.1f}")
105-
109+
106110
except pickle.UnpicklingError:
107111
print("Error: File content is corrupted and cannot be read.")
108112
except Exception as e:
109113
print(f"An unexpected error occurred: {str(e)}")
110114

115+
111116
if __name__ == "__main__":
112117
FILE_PATH = r"class.dat" # Update with your actual file path
113-
118+
114119
update_student_record(FILE_PATH)
115-
display_all_records(FILE_PATH)
120+
display_all_records(FILE_PATH)

1 File handle/File handle binary/Update a binary file2.py

Lines changed: 27 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -5,65 +5,70 @@
55
def initialize_file_if_not_exists(file_path: str) -> None:
66
"""
77
Check if file exists. If not, create it with an empty list of records.
8-
8+
99
Args:
1010
file_path (str): Path to the file.
11-
11+
1212
Raises:
1313
ValueError: If file_path is empty.
1414
"""
1515
if not file_path:
1616
raise ValueError("File path cannot be empty.")
17-
17+
1818
directory = os.path.dirname(file_path)
1919
if directory and not os.path.exists(directory):
2020
os.makedirs(directory, exist_ok=True)
21-
21+
2222
if not os.path.exists(file_path):
2323
with open(file_path, "wb") as f:
2424
pickle.dump([], f)
2525
print(f"Created new file: {file_path}")
2626

27+
2728
def update_student_record(file_path: str) -> None:
2829
"""
2930
Update a student's name and marks in the binary file by roll number.
30-
31+
3132
Args:
3233
file_path (str): Path to the binary file containing student records.
3334
"""
3435
initialize_file_if_not_exists(file_path)
35-
36+
3637
try:
3738
with open(file_path, "rb+") as f:
3839
# Load existing records
3940
records: list[tuple[int, str, int]] = pickle.load(f)
40-
41+
4142
if not records:
4243
print("No records found in the file.")
4344
return
44-
45+
4546
# Get roll number to update
4647
roll_to_update = int(input("Enter roll number to update: "))
4748
found = False
48-
49+
4950
# Find and update the record
5051
for i, record in enumerate(records):
5152
if record[0] == roll_to_update:
5253
current_name = record[1]
5354
current_marks = record[2]
54-
55+
5556
print("\nCurrent Record:")
5657
print(f"Roll: {roll_to_update}")
5758
print(f"Name: {current_name}")
5859
print(f"Marks: {current_marks}")
59-
60-
new_name = input("Enter new name (leave blank to keep current): ").strip()
61-
new_marks_input = input("Enter new marks (leave blank to keep current): ").strip()
62-
60+
61+
new_name = input(
62+
"Enter new name (leave blank to keep current): "
63+
).strip()
64+
new_marks_input = input(
65+
"Enter new marks (leave blank to keep current): "
66+
).strip()
67+
6368
# Update name if provided
6469
if new_name:
6570
records[i] = (record[0], new_name, record[2])
66-
71+
6772
# Update marks if provided
6873
if new_marks_input:
6974
try:
@@ -74,20 +79,20 @@ def update_student_record(file_path: str) -> None:
7479
records[i] = (record[0], record[1], new_marks)
7580
except ValueError:
7681
print("Invalid marks input. Marks not updated.")
77-
82+
7883
print("Record updated successfully.")
7984
found = True
8085
break
81-
86+
8287
if not found:
8388
print(f"Record with roll number {roll_to_update} not found.")
8489
return
85-
90+
8691
# Rewrite the entire file with updated records
8792
f.seek(0)
8893
pickle.dump(records, f)
8994
f.truncate() # Ensure any remaining data is removed
90-
95+
9196
# Display updated record
9297
f.seek(0)
9398
updated_records = pickle.load(f)
@@ -96,14 +101,15 @@ def update_student_record(file_path: str) -> None:
96101
print("-" * 35)
97102
for record in updated_records:
98103
print(f"{record[0]:<8}{record[1]:<15}{record[2]:<8}")
99-
104+
100105
except ValueError:
101106
print("Error: Invalid roll number. Please enter an integer.")
102107
except pickle.UnpicklingError:
103108
print("Error: File content is corrupted and cannot be read.")
104109
except Exception as e:
105110
print(f"An unexpected error occurred: {str(e)}")
106111

112+
107113
if __name__ == "__main__":
108114
FILE_PATH = r"studrec.dat" # Update with your actual file path
109-
update_student_record(FILE_PATH)
115+
update_student_record(FILE_PATH)

0 commit comments

Comments
 (0)