Build a Python-Based Electronic Attendance System: Step-by-Step Guide
This article outlines a student project to create a Python-powered electronic attendance system, detailing required CSV data formats, core functions such as loading data, login, record writing, and querying, along with task requirements, additional features, and complete code examples.
Project Overview
The school needs an electronic attendance system. Students have already learned Python for big‑data applications, so they are asked to implement the student‑side attendance features. Existing code provides part of the functionality; the remaining parts are marked with #todo comments.
Data Files
Student information is stored in stu_infos.csv. The first line contains column headers (student number, name, password) and each subsequent line holds a student's data.
Attendance records are stored in attendance.csv. The first line contains column headers (student number, name, time, attendance status). The status can be one of four values: "出勤" (present), "迟到" (late), "请假" (leave), "缺勤" (absent).
System Structure
The teacher side consists of two Python files: main.py – entry program that loads data, handles login, and adds attendance records. stu_attendance.py – defines functions for data loading, login, adding records, and querying.
Task Requirements
Append a line with your own information to stu_infos.csv (your real name and student number, password can be arbitrary).
Examine the #todo comments in the two Python files, add the appropriate code, and provide the added code snippets.
Test the program, capture screenshots, and verify two scenarios: three consecutive login failures and a successful login followed by adding an attendance record.
Additional Feature
Add a query function that, given a student's name, returns all of that student's attendance records.
Import Modules
import csv
import time
student_infos = []Load Data
def load_stu_info():
"""Load student information from stu_infos.csv"""
with open("stu_infos.csv", encoding='utf-8-sig') as file:
f_csv = csv.reader(file)
header = next(f_csv)
for row in f_csv:
student_info = {}
for index in range(3):
student_info[header[index]] = row[index]
student_infos.append(student_info)Login
def login():
"""User logs in with student number and password.
Allows up to three attempts; returns (True, student_no) on success,
otherwise (False, None)."""
retry_time = 0
while retry_time < 3:
user_no = input('请输入登录账号:')
password = input('请输入密码:')
for i in student_infos:
if i['no'] == user_no and i['password'] == password:
return True, user_no
print('用户名或者密码错误!!!请重新输入。')
retry_time += 1
else:
return False, NoneAdd Attendance Record
def add(user_no):
for x in student_infos:
if user_no == x['no']:
name = x['name']
break
times = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
choices = ['出勤', '迟到', '请假', '缺勤']
a = int(input("\t该学生出勤情况:1-出勤\t2-迟到\t3-请假\t4-缺勤:"))
if a == 1:
data = choices[0]
elif a == 2:
data = choices[1]
elif a == 3:
data = choices[2]
else:
data = choices[3]
with open("attendance.csv", 'a+', newline='', encoding='utf-8') as f:
wf = csv.writer(f)
wf.writerow([user_no, name, times, data])
print("{}同学{}数据已经写入成功!操作时间是{}".format(name, data, times))Query Attendance Records
def select():
student = []
with open("attendance.csv", encoding='utf-8-sig') as file:
f_csv = csv.reader(file)
header = next(f_csv)
for row in f_csv:
students = {}
for index in range(4):
students[header[index]] = row[index]
student.append(students)
name = input("请输入你需要查找的姓名:")
print(" 学号\t\t姓名\t\t操作时间\t\t出勤状态")
for a in student:
if a['name'] == name:
print(a['no'] + '\t' + a['name'] + '\t' + a['time'] + '\t\t' + a['state'])
else:
print("无此人!!!")
breakMain Function (main.py)
from student.stu_attendance import *
if __name__ == '__main__':
load_stu_info()
success, stu_no = login()
print(stu_no)
if success:
print('登录成功!')
add(stu_no)
q = int(input("你想要查询出勤数据吗?\tyes(1)--no(0)"))
if q == 1:
select()
else:
print('欢迎下次登录电子考勤系统')
else:
print('登录失败')Running Effect
Screenshot examples of the program’s execution are shown below.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
