1 def read_stus():
2
3
4
5
6 if os
.path
.exists
(file_name
):
7 f
=open(file_name
,"r")
8 while True:
9 student_str
=f
.readline
10 if student_str
=="":
11 break
12 else:
13 student_info_list
=student_str
.split
("\t")
14 student
={"name":student_info_list
[0],"age":student_info_list
[1],"num":student_info_list
[2]}
15 stus
.append
(student
)
16
17 def write_stus_to_file():
18 if os
.path
.exists
(file_name
):
19 if os
.path
.exists
(backup_file
):
20 os
.remove
(backup_file
)
21 os
.rename
(file_name
,"backup-"+file_name
)
22 f
=open(file_name
,"w")
23 for student
in stus
:
24 student_str
="%s\t%s\t%s\n"%(student
['name'],student
['age'],student
['num'])
25 f
.write
(student_str
)
26 f
.close
()
27
28 def print_menu():
29 print("~"*30)
30 print("学生管理系统".center
(30))
31 print("输入1:添加学生")
32 print("输入2:查找学生")
33 print("输入3: 修改学生")
34 print("输入4: 删除学生")
35 print("输入5: 查看所有学生")
36 print("输入6: 退出")
37
38 def add_student():
39 name
=input("请输入学生的姓名:")
40 age
=int(input("请输入学生的年龄:"))
41 num
=input("请输入学生的学号:")
42
43
44 stu
={}
45 stu
["name"]=name
46 stu
["age"]=age
47 stu
["num"]=num
48 stus
.append
(stu
)
49 print("添加成功")
50
51 def search_student(name
):
52 for item
in stus
:
53 if item
["name"]==name
.strip
():
54 print("%s 学生存在"%name
)
55 print_student
(item
)
52 for item
in stus
:
53 if item
["name"]==name
.strip
():
54 print("%s 学生存在"%name
)
55 print_student
(item
)
56 return item
57 else:
58 print("学生%s没有找到"%name
)
59
60 def print_student(item
):
61 print("%s\t%s\t%s"%(item
["name"],item
["age"],item
["num"]))
62
63 def print_all_students():
64 print("序号\t姓名\t年龄\t学号")
65 for i
,item
in enumerate(stus
,1):
66 print("%s\t"%i
,end
="")
67 print_student
(item
)
68
69 def del_student(name
):
70 student
=search_student
(name
)
71 for item
in stus
:
72 if item
["name"]==name
.strip
():
73 stus
.remove
(student
)
74 else:
75 print("学生%s没有找到"%name
)
76
77 def main():
78 print_menu
()
79 read_stus
()
80 while True:
81 operate
=input("请输入你想要的操作:")
82 if operate
=="1":
83 add_student
()
84 write_stus_to_file
()
85 if operate
=="2":
86 name
=input("请输入要查找的学生的姓名:")
87 search_student
(name
)
88 if operate
== "3":
89 pass
90 if operate
=="4":
91 name
=input("请输入要删除的学生姓名:")
92 del_student
(name
)
93 print("删除学生%s成功"%name
)
94 write_stus_to_file
()
95 if operate
=="5":
96 print_all_students
()
97 if operate
=="6":
98 break
99 file_name
="stus.txt"
100 backup_file
="backup-stus.txt"
101
102 stus
=[]
103 main
()
注:第六行判断只可执行一次,第二次将会报错(文件以及存在) *个人想法,难免缺陷,有更好思路欢迎交流哦 ~~ (超小声哀求)~在线等一个信息修改的实现,欢迎各路神仙补充——>
转载请注明原文地址: https://lol.8miu.com/read-6979.html