Attendance_system / record_attendance.py
PRIYANSHUDHAKED's picture
Upload record_attendance.py
216f34f verified
raw
history blame
2.67 kB
import csv
import os
from datetime import datetime
def record_attendance_new(present_students: list, subject: str):
# Automatically get the current date in YYYY-MM-DD format
date = datetime.now().strftime("%Y-%m-%d")
# Create or open the CSV file based on the subject
csv_file_path = f'{subject}.csv'
# Check if the file exists
if not os.path.exists(csv_file_path):
# If the file doesn't exist, create it and add the date as the first column header
with open(csv_file_path, 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['Roll Number', date]) # Initialize with Roll Number as the first column
for roll_number in present_students:
writer.writerow([roll_number]) # Insert the roll numbers under the date column
else:
# If the file exists, open it and check the structure
# Read the existing CSV file
with open(csv_file_path, 'r', newline='') as csvfile:
reader = csv.reader(csvfile)
rows = list(reader)
# Check if the date column already exists
if date not in rows[0]:
# Add a new date column if it doesn't exist
rows[0].append(date)
# Collect the index of the date column
date_col_index = rows[0].index(date)
# Update or add roll numbers for the given date
for roll_number in present_students:
# Check if the roll number already exists in the file
found = False
for row in rows[1:]:
if row[0] == str(roll_number): # Roll number matches
found = True
# If the roll number is found and the corresponding date cell is empty, fill it
if len(row) < date_col_index + 1: # Extend the row if it doesn't have enough columns
row.extend([''] * (date_col_index - len(row) + 1))
if row[date_col_index] == '':
row[date_col_index] = 'Present'
break
if not found:
# If the roll number is not found, add a new row for this roll number
new_row = [str(roll_number)] + [''] * (date_col_index - 1) + ['Present']
rows.append(new_row)
# Write the updated data back to the CSV file
with open(csv_file_path, 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerows(rows)
print(f"Attendance recorded for {len(present_students)} students on {date} in {subject}.")