python assignment.pdf
python assignment.pdf
✅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}")
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)
class Student:
def __init__(self):
self.students = {}
Python Assignment 2
self.students[roll] = {"name": name, "marks": {}}
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()
Python Assignment 4
print("Book not available.")
# 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)
Python Assignment 5
import re
import os
validate_phone("9876543210")
validate_phone("12345abcde")
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