Python Assignment
✅System
Q1: CSV File as Database + Transaction Management
import csv
import os
import tempfile
from datetime import datetime
EMPLOYEE_CSV = '[Link]'
def connect_to_csv(filepath):
if not [Link](filepath):
with open(filepath, 'w', newline='') as file:
writer = [Link](file)
[Link](['ID', 'Name', 'Position', 'Dept', 'Hire Date'])
return filepath
def read_employees(filepath):
try:
with open(filepath, 'r') as file:
reader = [Link](file)
for row in reader:
print(row)
except Exception as e:
print(f"Error reading file: {e}")
def write_employee(filepath, emp_data, delimiter=','):
try:
with open(filepath, 'a', newline='') as file:
writer = [Link](file, delimiter=delimiter)
[Link](emp_data)
print("Employee added.")
except Exception as e:
print(f"Error writing to file: {e}")
Python Assignment 1
def transactional_update(filepath, new_data_list):
try:
temp_fd, temp_path = [Link]()
with open(temp_path, 'w', newline='') as temp_file:
writer = [Link](temp_file)
[Link](['ID', 'Name', 'Position', 'Dept', 'Hire Date'])
for data in new_data_list:
[Link](data)
[Link](temp_path, filepath)
print("Transaction completed successfully.")
except Exception as e:
print(f"Transaction failed: {e}")
# Example Usage
connect_to_csv(EMPLOYEE_CSV)
write_employee(EMPLOYEE_CSV, ['101', 'Alice', 'Engineer', 'R&D', '2023-08-
01'])
read_employees(EMPLOYEE_CSV)
new_employees = [
['102', 'Bob', 'Manager', 'HR', '2021-01-12'],
['103', 'Eve', 'Analyst', 'Finance', '2022-04-05']
]
transactional_update(EMPLOYEE_CSV, new_employees)
read_employees(EMPLOYEE_CSV)
✅ Q2: Student and Library Management System
import sqlite3
from datetime import date
class Student:
def __init__(self):
[Link] = {}
def add_student(self, roll, name):
Python Assignment 2
[Link][roll] = {"name": name, "marks": {}}
def add_marks(self, roll, subject, mark):
if roll in [Link]:
[Link][roll]['marks'][subject] = mark
else:
print("Student not found!")
def calc_average(self, roll):
marks = [Link][roll]["marks"].values()
return sum(marks) / len(marks) if marks else 0
def display_student(self, roll):
student = [Link](roll)
if student:
avg = self.calc_average(roll)
print(f"Roll: {roll}, Name: {student['name']}, Marks: {student['mark
s']}, Avg: {avg:.2f}")
else:
print("Student not found.")
def list_students(self):
for roll in [Link]:
self.display_student(roll)
class LibraryDB:
def __init__(self, db_name='[Link]'):
[Link] = [Link](db_name)
self.create_tables()
def create_tables(self):
cursor = [Link]()
[Link]('''CREATE TABLE IF NOT EXISTS books (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT, author TEXT, is_available INTEGER)''')
[Link]('''CREATE TABLE IF NOT EXISTS borrow_records (
book_id INTEGER, roll_no INTEGER,
borrow_date TEXT, return_date TEXT)''')
Python Assignment 3
[Link]()
def add_book(self, title, author):
cursor = [Link]()
[Link]("INSERT INTO books (title, author, is_available) VALUE
S (?, ?, 1)", (title, author))
[Link]()
def list_books(self, available_only=False):
cursor = [Link]()
if available_only:
[Link]("SELECT * FROM books WHERE is_available = 1")
else:
[Link]("SELECT * FROM books")
for book in [Link]():
print(book)
def search_books(self, keyword):
cursor = [Link]()
[Link]("SELECT * FROM books WHERE title LIKE ? OR author
LIKE ?", (f"%{keyword}%", f"%{keyword}%"))
for book in [Link]():
print(book)
def borrow_book(self, book_id, roll_no):
cursor = [Link]()
[Link]("SELECT is_available FROM books WHERE id = ?", (bo
ok_id,))
result = [Link]()
if result and result[0] == 1:
[Link]("UPDATE books SET is_available = 0 WHERE id = ?",
(book_id,))
[Link]("INSERT INTO borrow_records (book_id, roll_no, bor
row_date, return_date) VALUES (?, ?, ?, NULL)",
(book_id, roll_no, [Link]()))
[Link]()
print("Book borrowed.")
else:
Python Assignment 4
print("Book not available.")
def return_book(self, book_id):
cursor = [Link]()
[Link]("UPDATE books SET is_available = 1 WHERE id = ?", (b
ook_id,))
[Link]("UPDATE borrow_records SET return_date = ? WHERE
book_id = ? AND return_date IS NULL", ([Link](), book_id))
[Link]()
print("Book returned.")
def books_by_student(self, roll_no):
cursor = [Link]()
[Link]("SELECT * FROM borrow_records WHERE roll_no = ?",
(roll_no,))
for record in [Link]():
print(record)
# Example Integration
student_mgr = Student()
lib = LibraryDB()
student_mgr.add_student(1, "John")
student_mgr.add_marks(1, "Math", 95)
student_mgr.add_marks(1, "Science", 88)
student_mgr.display_student(1)
lib.add_book("Python Basics", "Guido")
lib.add_book("Data Science", "Wes McKinney")
lib.list_books()
lib.borrow_book(1, 1)
lib.books_by_student(1)
lib.return_book(1)
✅ Q3: Regex, File Handling, List Deduplication
Python Assignment 5
import re
import os
# 1. Validate 10-digit phone number
def validate_phone(number):
if [Link](r'\d{10}', number):
print("Valid number.")
else:
print("Invalid number.")
validate_phone("9876543210")
validate_phone("12345abcde")
# 2. File Reading with seek & tell
file_path = '[Link]'
if [Link](file_path):
with open(file_path, 'r') as f:
print("Initial Position:", [Link]())
content = [Link]()
print("File Content:\n", content)
[Link](0)
print("After Seek Position:", [Link]())
else:
print("File not found.")
# 3. Remove duplicates from list
def remove_duplicates(lst):
return list(set(lst))
original_list = [1, 2, 2, 3, 4, 4, 5]
unique_list = remove_duplicates(original_list)
print("Original:", original_list)
print("Unique:", unique_list)
Python Assignment 6