Python Assignment
✅System
Q1: CSV File as Database + Transaction Management
import csv
import os
import tempfile
from datetime import datetime
EMPLOYEE_CSV = 'employees.csv'
def connect_to_csv(filepath):
if not os.path.exists(filepath):
with open(filepath, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['ID', 'Name', 'Position', 'Dept', 'Hire Date'])
return filepath
def read_employees(filepath):
try:
with open(filepath, 'r') as file:
reader = csv.DictReader(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 = csv.writer(file, delimiter=delimiter)
writer.writerow(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 = tempfile.mkstemp()
with open(temp_path, 'w', newline='') as temp_file:
writer = csv.writer(temp_file)
writer.writerow(['ID', 'Name', 'Position', 'Dept', 'Hire Date'])
for data in new_data_list:
writer.writerow(data)
os.replace(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):
self.students = {}
def add_student(self, roll, name):
Python Assignment 2
self.students[roll] = {"name": name, "marks": {}}
def add_marks(self, roll, subject, mark):
if roll in self.students:
self.students[roll]['marks'][subject] = mark
else:
print("Student not found!")
def calc_average(self, roll):
marks = self.students[roll]["marks"].values()
return sum(marks) / len(marks) if marks else 0
def display_student(self, roll):
student = self.students.get(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 self.students:
self.display_student(roll)
class LibraryDB:
def __init__(self, db_name='library.db'):
self.conn = sqlite3.connect(db_name)
self.create_tables()
def create_tables(self):
cursor = self.conn.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS books (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT, author TEXT, is_available INTEGER)''')
cursor.execute('''CREATE TABLE IF NOT EXISTS borrow_records (
book_id INTEGER, roll_no INTEGER,
borrow_date TEXT, return_date TEXT)''')
Python Assignment 3
self.conn.commit()
def add_book(self, title, author):
cursor = self.conn.cursor()
cursor.execute("INSERT INTO books (title, author, is_available) VALUE
S (?, ?, 1)", (title, author))
self.conn.commit()
def list_books(self, available_only=False):
cursor = self.conn.cursor()
if available_only:
cursor.execute("SELECT * FROM books WHERE is_available = 1")
else:
cursor.execute("SELECT * FROM books")
for book in cursor.fetchall():
print(book)
def search_books(self, keyword):
cursor = self.conn.cursor()
cursor.execute("SELECT * FROM books WHERE title LIKE ? OR author
LIKE ?", (f"%{keyword}%", f"%{keyword}%"))
for book in cursor.fetchall():
print(book)
def borrow_book(self, book_id, roll_no):
cursor = self.conn.cursor()
cursor.execute("SELECT is_available FROM books WHERE id = ?", (bo
ok_id,))
result = cursor.fetchone()
if result and result[0] == 1:
cursor.execute("UPDATE books SET is_available = 0 WHERE id = ?",
(book_id,))
cursor.execute("INSERT INTO borrow_records (book_id, roll_no, bor
row_date, return_date) VALUES (?, ?, ?, NULL)",
(book_id, roll_no, date.today()))
self.conn.commit()
print("Book borrowed.")
else:
Python Assignment 4
print("Book not available.")
def return_book(self, book_id):
cursor = self.conn.cursor()
cursor.execute("UPDATE books SET is_available = 1 WHERE id = ?", (b
ook_id,))
cursor.execute("UPDATE borrow_records SET return_date = ? WHERE
book_id = ? AND return_date IS NULL", (date.today(), book_id))
self.conn.commit()
print("Book returned.")
def books_by_student(self, roll_no):
cursor = self.conn.cursor()
cursor.execute("SELECT * FROM borrow_records WHERE roll_no = ?",
(roll_no,))
for record in cursor.fetchall():
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 re.fullmatch(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 = 'sample.txt'
if os.path.exists(file_path):
with open(file_path, 'r') as f:
print("Initial Position:", f.tell())
content = f.read()
print("File Content:\n", content)
f.seek(0)
print("After Seek Position:", f.tell())
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