#encoding = 'UTF-8' ''' @author:xianyt @func:实现简单的从文件读取和写入学生信息的项目 @date:2018/8/21 ''' with open('stu.txt', 'r') as f: #取出文件内容 student_list = f.read() if student_list=='': student_list=[] else: student_list = eval(student_list) def add_student(): #添加 name = input('请输入新学员姓名:') age= input('请输入新学员年龄:') number= input('请输入新学员学号:') student_list.append(locals()) with open('stu.txt','w+') as f: f.write(str(student_list)) #文件写入只能写入字符和二进制编码 def find_student(): #查询 f_number=input('请输入要查询的学号:') for student in student_list: if student['number']==f_number: print('找到了,信息如下:姓名:{},年龄:{},学号:{}'.format(student['name'],student['age'],student['number'])) break else: print('没找到') def update_student(): # 修改 f_number = input('请输入要修改的学生学号:') for student in student_list: if student['number']==f_number: new_name=input('请输入修改后的名字:') new_age = input('请输入修改后的年龄:') student['name']=new_name student['age']=new_age with open('stu.txt','w+') as f: f.write(str(student_list)) break else: print('班级里没有这个学号的人') def del_student(): # 删除 f_number = input('请输入要删除的学生学号:') for student in student_list: if student['number']==f_number: student_list.remove(student) with open('stu.txt',"w+") as f: f.write(str(student_list)) break else: print('班级里没有这个学号的人') def student_main(): print(''' =====欢迎进入学生信息管理系统===== 1.添加学员信息 2.查询学员信息 3.修改学员信息 4.删除学员信息 5.退出 ''') while True: num = int(input('请选择功能:')) if num == 1: add_student() elif num == 2: find_student() elif num == 3: update_student() elif num == 4: del_student() elif num == 5: break else: print('输入有误,请重新输入') student_main()