# 添加、删除、显示学生信息(保存)
# 保存所有学生信息
students = {}
# 创建
ID = 1000
# 控制系统是否退出
flag = True
# 从文件中读取学生信息
def load_students():
# 加载学生信息从文件中
stu_file = open("students.txt","r")
# 读取文件内容
stus = stu_file.readlines()
global students
# 解析文件数据
max_id = 0
for stu in stus:
#去掉字符串最尾部的换行符\n
stu_list =stu[0:-1].split(",")
#学生信息转成字典类型
s_info = {}
s_info["name"] = stu_list[1]
s_info["score"] = stu_list[2]
#将学生数据写会students字典中
id = int(stu_list[0])
students[id] = s_info
if id > max_id:
max_id = id
ID = max_id
def save_students():
# 保存学生信息到文件
# 1.将每一个学生的信息,拼接成一个字符串
stu_info = []
stu_file = open("students.txt","w")
for k, v in students.items():
stu_info.append(str(k))
stu_info.append(v["name"])
stu_info.append(v["score"])
stu_data = ",".join(stu_info)
stu_data = stu_data + "\n"
stu_file.write(stu_data)
stu_info.clear()
# 关闭文件
stu_file.close()
def add_student():
# 添加新学生
global students
global ID
stu_name = input("请输入新学生的姓名:")
stu_score = input("请输入新学生的分数:")
# 构建学生的字典
stu_info = {}
stu_info["name"] = stu_name
stu_info["score"] = stu_score
#递增ID
ID += 1
# 将新学生添加学生字典中
students[ID] = stu_info
def show_students():
# 显示所有学生信息
for k, v in students.items():
print("学号:%d\t姓名:%s\t分数:%s"%(k, v["name"], v["score"]))
print("----------------")
defremove_student():
# 删除学生信息根据学生编号
delete_id =int(input("请输入要删除学生的学号:"))
# 判断要删除学生的编号是否存在
global students
if delete_id in students.keys():
del students[delete_id]
print("删除编号为%d的学生成功!" % delete_id)
else:
print("您输入的编号有误!")
defshow_operation():
print("请选择操作:")
print("1.添加学生")
print("2.删除学生")
print("3.显示学生")
print("4.退出系统")
print("------------")
# 加载数据
load_students()
while flag:
print("欢迎使用学生管理系统v1.0")
# 显示菜单
show_operation()
operation = input("请输入您的操作:")
if operation == "1":
add_student()
elif operation == "2":
remove_student()
elif operation == "3":
show_students()
elif operation == "4":
print("欢迎再次使用本系统!")
flag = False
save_students()
else:
print("操作有误,请重新输入!")