python 学生管理系统 文件版 增删改查
# 在程序开始之前完成数据的读取 # 存在着循环 # 循环的内容 # 将操作内容分解为函数 def sel_student(students_list): """ 查看所有学生信息 :param students_list: 所有的学生信息 :return: """ print("id\t\t姓名\t\t性别\t\t年龄\t\t班级") for i in students_list: print("%s\t\t%s\t\t%s\t\t%s\t\t%s" % (i["id"], i["name"], i["sex"], i["age"], i["className"])) def add_student(students_list): print("请输入新学生的相关信息:") id = input("请输入id:") name = input("请输入姓名:") sex = input("请输入性别:") age = input("请输入年龄:") className = input("请输入班级:") context = { "students_list": students_list, "message": "" } # 校验参数是否为空 if not all([id, name, sex, age, className]): context["message"] = "缺失参数" return context # 校验id是否重复 if id in [i['id'] for i in students_list ]: context["message"] = "id重复" return context # 校验性别是否合法 if sex not in ["男", "女"]: context["message"] = "性别错误" return context new_student = {} new_student["id"] = id new_student["name"] = name new_student["sex"] = sex new_student["age"] = age new_student["className"] = className students_list.append(new_student) context["message"] = "成功" return context def edit_student(students_list): info = input("请输入要修改的学生id") id = input("请输入新id:") name = input("请输入新姓名:") sex = input("请输入新性别:") age = input("请输入新年龄:") className = input("请输入新班级:") for i in students_list: if info == i["id"]: i["id"] = id i["name"] = name i["sex"] = sex i["age"] = age i["className"] = className return "成功" def del_student(students_list): info = input("请输入删除的学生id") for i in students_list: if info == i["id"]: students_list.remove(i) return "成功" return "未找到该学生" def read_data(): """ 初始化数据,从data.txt中读取相关的数据 :return: 返回列表数据 """ # 1. 读取文件数据 f = open("data.txt", encoding="utf-8") students_list = [] for i in f.readlines(): student_list = i.strip().split(" ") student = {} # 造一个空的字典 student["id"] = student_list[0] student["name"] = student_list[1] student["sex"] = student_list[2] student["age"] = student_list[3] student["className"] = student_list[4] # 2. 转换数据 students_list.append(student) print(students_list) f.close() return students_list def save_data(students_list): """ 保存到文件 :param students_list: 学生数据 :return: """ f = open("data.txt", "w", encoding="utf-8") for i in students_list: f.write("%s %s %s %s %s\n" % (i["id"], i["name"], i["sex"], i["age"], i["className"])) f.close() def main(): students_list = read_data() while True: print(""" 欢迎使用本系统! 1. 查看学生信息 2. 增加学生信息 3. 修改学生信息 4. 删除学生信息 5. 退出 """) info = input("请输入你的选择:") while info not in ["1", "2", "3", "4", "5"]: print("输入错误,请重新输入!") info = input("请输入你的选择:") if info == "1": sel_student(students_list) elif info == "2": res = add_student(students_list) elif info == "3": edit_student(students_list) elif info == "4": del_student(students_list) else: print("本次操作结束,欢迎下次使用!") break if __name__ == '__main__': main()