Python循环中修改文本文件指定行实现考勤记录问题求助
解决文本文件更新考勤记录的问题
你的代码目前存在几个核心问题:
- 仅读取文件但未执行写入操作,修改后的数据无法保存到文件
- 学生序号
i每次循环都重置为1,无法正确显示学生编号 - 未处理缺勤的逻辑分支
- 模块选择只覆盖了SOFT_6017的情况,缺少SOFT_6018的处理
- 读取行时未处理换行符,可能导致split后的数据包含多余的换行符
下面是修复并完善后的代码:
def record_attendence(): print("Module Record System - Attendance - Choose a Module") print("-"*50) print("1: SOFT_6017") print("2: SOFT_6018") # 处理用户输入,避免非整数输入报错 try: module = int(input("Enter module number: ")) except ValueError: print("Invalid input, please enter 1 or 2") return # 映射模块编号到文件名 module_files = {1: "SOFT_6017.txt", 2: "SOFT_6018.txt"} if module not in module_files: print("Invalid module number, please choose 1 or 2") return filename = module_files[module] # 读取文件所有内容到列表,方便修改 with open(filename, 'r') as f: lines = [line.strip() for line in f.readlines() if line.strip()] # 去除空行和换行符 # 遍历处理每个学生的考勤 updated_lines = [] for i, line in enumerate(lines, start=1): parts = line.split(':') student_name = parts[0] present_count = int(parts[1]) absent_count = int(parts[2]) print(f"\nStudent #{i}: {student_name}") print("1: present") print("2: absent") try: attendence = int(input("Enter choice: ")) except ValueError: print("Invalid input, defaulting to absent") attendence = 2 # 更新考勤计数 if attendence == 1: present_count += 1 elif attendence == 2: absent_count += 1 else: print("Invalid choice, no changes made for this student") # 重新拼接成行 updated_line = f"{student_name}:{present_count}:{absent_count}" updated_lines.append(updated_line) # 将修改后的内容写入文件 with open(filename, 'w') as f: f.write('\n'.join(updated_lines)) print("\nAttendance records updated successfully!") def main(): record_attendence() if __name__ == "__main__": main()
关键改进点说明:
- 文件读写逻辑:先把所有行读取到列表,修改完成后一次性写入文件,避免边读边写的冲突问题
- 序号处理:使用
enumerate(lines, start=1)自动生成从1开始的学生序号 - 错误处理:添加了
try-except捕获非整数输入,避免程序崩溃 - 考勤逻辑:完善了缺勤的计数更新分支
- 模块选择:用字典映射模块编号和文件名,扩展更方便,同时增加了无效输入的提示
- 换行符处理:读取时用
strip()去除每行的换行符和空白,避免处理时出现异常
文本文件格式说明
保持你原来的格式即可:
Micheal Martin:0:0 Bob Wade:0:0 Sarah Norton:0:0
内容的提问来源于stack exchange,提问作者Anuka Kuruppuarachchi
相关产品推荐
相关产品推荐

