import csv import os from datetime import datetime import streamlit as st def record_attendance_new(present_students: list, subject: str, max_roll_number=26): # Automatically get the current date in YYYY-MM-DD format date = datetime.now().strftime("%Y-%m-%d") # Convert present_students to integers present_students = list(map(int, present_students)) print("Present Students:", present_students) # Debugging line # Get the path of the uploaded CSV file csv_file_path = f'{subject}.csv' print("CSV File Path:", csv_file_path) # Debugging line # Read the existing CSV file if os.path.exists(csv_file_path): with open(csv_file_path, 'r', newline='') as csvfile: reader = csv.reader(csvfile) rows = list(reader) else: # If file doesn't exist, create a new one with header rows = [['Roll Number']] # Check if the date column already exists if date not in rows[0]: rows[0].append(date) date_col_index = rows[0].index(date) # Update or add attendance for each roll number for roll_number in range(1, max_roll_number + 1): found = False for row in rows[1:]: if int(row[0]) == roll_number: found = True if len(row) < date_col_index + 1: row.extend([''] * (date_col_index - len(row) + 1)) if roll_number in present_students: row[date_col_index] = 'Present' print(f"Updating {roll_number}: Present") # Debugging line else: row[date_col_index] = 'Absent' print(f"Updating {roll_number}: Absent") # Debugging line break if not found: new_row = [str(roll_number)] + [''] * (date_col_index - 1) new_row.append('Present' if roll_number in present_students else 'Absent') rows.append(new_row) print(f"Adding new row for {roll_number}: {'Present' if roll_number in present_students else 'Absent'}") # 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) # Create a download button with open(csv_file_path, 'r') as file: csv_contents = file.read() st.download_button( label="Download updated attendance file", data=csv_contents, file_name=csv_file_path, mime='text/csv' ) print(f"Attendance recorded for {len(present_students)} students on {date} in {subject}.")