Skip to content

fix bugs and fix ruff and workflows #2796

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions .github/workflows/Python CI.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
name: Python CI
on: [pull_request, push]
jobs:
lint_python:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4

- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.13"
cache: "pip"
cache-dependency-path: "pyproject.toml"

- name: Install check dependencies
run: |
python -m pip install --upgrade pip wheel
pip install bandit ruff mypy safety codespell

- name: Run Codespell
run: codespell --config pyproject.toml || true

- name: Run Bandit
run: bandit --recursive --skip B101 . || true

- name: Run Ruff (linting)
run: ruff check . --config pyproject.toml

- name: Run Ruff (formatting check)
run: ruff format --check . --config pyproject.toml || true



- name: Setup Mypy cache
run: mkdir -p .mypy_cache

- name: Install type stubs
run: mypy --config-file pyproject.toml --install-types --non-interactive

- name: Run Mypy
run: mypy --config-file pyproject.toml
24 changes: 0 additions & 24 deletions .github/workflows/lint_python.yml

This file was deleted.

7 changes: 4 additions & 3 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
.idea
.vscode
_pycache_
*.pyc
string=sorted(input())
lower=""
Expand All @@ -18,10 +20,9 @@ print(lower+upper+odd+even)

.venv
# operating system-related files

# file properties cache/storage on macOS
*.DS_Store

# thumbnail cache on Windows
Thumbs.db
bankmanaging.db
bankmanaging.db
.vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,17 +1,51 @@
import pickle
from typing import List, Tuple

def delete_student_record() -> None:
"""
Delete a student record from the binary data file 'studrec.dat' based on the provided roll number.

This function performs the following operations:
1. Reads the current student records from 'studrec.dat'
2. Prompts the user to enter a roll number to delete
3. Removes the record with the specified roll number
4. Writes the updated records back to 'studrec.dat'

Each student record is stored as a tuple in the format: (roll_number, ...)

Raises:
FileNotFoundError: If 'studrec.dat' does not exist.
pickle.UnpicklingError: If the file contains corrupted data.
ValueError: If the user input cannot be converted to an integer.
"""
try:
# Read existing student records from file
with open("studrec.dat", "rb") as file:
student_records: List[Tuple[int, ...]] = pickle.load(file)
print("Current student records:", student_records)

# Get roll number to delete
roll_number: int = int(input("Enter the roll number to delete: "))

# Filter out the record with the specified roll number
updated_records: List[Tuple[int, ...]] = [
record for record in student_records if record[0] != roll_number
]

# Write updated records back to file
with open("studrec.dat", "wb") as file:
pickle.dump(updated_records, file)

print(f"Record with roll number {roll_number} has been deleted.")

except FileNotFoundError:
print("Error: The file 'studrec.dat' does not exist.")
except pickle.UnpicklingError:
print("Error: The file contains corrupted data.")
except ValueError as e:
print(f"Error: Invalid input. Please enter an integer. {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")

def bdelete():
# Opening a file & loading it
with open("studrec.dat","rb") as F:
stud = pickle.load(F)
print(stud)

# Deleting the Roll no. entered by user
rno = int(input("Enter the Roll no. to be deleted: "))
with open("studrec.dat","wb") as F:
rec = [i for i in stud if i[0] != rno]
pickle.dump(rec, F)


bdelete()
if __name__ == "__main__":
delete_student_record()
Original file line number Diff line number Diff line change
@@ -1,23 +1,47 @@
import os
import pickle


def binary_read():
with open("studrec.dat","rb") as b:
stud = pickle.load(b)
print(stud)

# prints the whole record in nested list format
print("contents of binary file")

for ch in stud:

print(ch) # prints one of the chosen rec in list

rno = ch[0]
rname = ch[1] # due to unpacking the val not printed in list format
rmark = ch[2]

print(rno, rname, rmark, end="\t")


binary_read()
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()
135 changes: 110 additions & 25 deletions 1 File handle/File handle binary/Update a binary file.py
Original file line number Diff line number Diff line change
@@ -1,30 +1,115 @@
# Updating records in a binary file

import os
import pickle
from typing import List, Tuple

def initialize_file_if_not_exists(file_path: str) -> None:
"""
Check if file exists. If not, create it with an empty list of records.

Args:
file_path (str): Path to the file.

Raises:
ValueError: If file_path is empty.
"""
if not file_path:
raise ValueError("File path cannot be empty.")

directory = os.path.dirname(file_path)
if directory and not os.path.exists(directory):
os.makedirs(directory, exist_ok=True)

if not os.path.exists(file_path):
with open(file_path, "wb") as f:
pickle.dump([], f)
print(f"Created new file: {file_path}")

def update():
with open("class.dat", "rb+") as F:
S = pickle.load(F)
found = False
rno = int(input("enter the roll number you want to update"))

for i in S:
if rno == i[0]:
print(f"the currrent name is {i[1]}")
i[1] = input("enter the new name")
found = True
break

if found:
print("Record not found")

else:
F.seek(0)
pickle.dump(S, F)

def update_student_record(file_path: str) -> None:
"""
Update a student's name in the binary file by roll number.

Args:
file_path (str): Path to the binary file containing student records.
"""
initialize_file_if_not_exists(file_path)

try:
with open(file_path, "rb+") as f:
# Load existing records
records: List[Tuple[int, str, float]] = pickle.load(f)

if not records:
print("No records found in the file.")
return

# Get roll number to update
roll_to_update = int(input("Enter roll number to update: "))
found = False

# Find and update the record
for i, record in enumerate(records):
if record[0] == roll_to_update:
current_name = record[1]
new_name = input(f"Current name: {current_name}. Enter new name: ").strip()

if new_name:
# Create a new tuple with updated name
updated_record = (record[0], new_name, record[2])
records[i] = updated_record
print("Record updated successfully.")
else:
print("Name cannot be empty. Update cancelled.")

found = True
break

if not found:
print(f"Record with roll number {roll_to_update} not found.")
return

# Rewrite the entire file with updated records
f.seek(0)
pickle.dump(records, f)
f.truncate() # Ensure any remaining data is removed

except ValueError:
print("Error: Invalid roll number. Please enter an integer.")
except pickle.UnpicklingError:
print("Error: File content is corrupted and cannot be read.")
except Exception as e:
print(f"An unexpected error occurred: {str(e)}")

update()
def display_all_records(file_path: str) -> None:
"""
Display all student records in the binary file.

Args:
file_path (str): Path to the binary file.
"""
initialize_file_if_not_exists(file_path)

try:
with open(file_path, "rb") as f:
records: List[Tuple[int, str, float]] = pickle.load(f)

if not records:
print("No records found in the file.")
return

print("\nAll Student Records:")
print(f"{'ROLL':<8}{'NAME':<20}{'PERCENTAGE':<12}")
print("-" * 40)

for record in records:
print(f"{record[0]:<8}{record[1]:<20}{record[2]:<12.1f}")

except pickle.UnpicklingError:
print("Error: File content is corrupted and cannot be read.")
except Exception as e:
print(f"An unexpected error occurred: {str(e)}")

with open("class.dat", "rb") as F:
print(pickle.load(F))
if __name__ == "__main__":
FILE_PATH = r"class.dat" # Update with your actual file path

update_student_record(FILE_PATH)
display_all_records(FILE_PATH)
Loading
Loading