Spaces:
Runtime error
Runtime error
File size: 2,671 Bytes
216f34f |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
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}.")
|