python+文件操作实现学生管理系统
import os.path
class Student(object):
def __init__(self, id_s, name, age, gender):
self.id_s = id_s
self.name = name
self.age = age
self.gender = gender
def __repr__(self):
return f"{self.id_s}\t{self.name}\t{self.age}\t{self.gender}"
class Administrator(object):
dict_s = {}
file = "file_message"
@staticmethod
def add_message():
id_s = input("请输入学生ID:")
for key in Administrator.dict_s:
if key == id_s:
print("学生已经存在!!!")
break
else:
name = input("请输入学生姓名:")
age = input("请输入学生年龄:")
gender = input("请输入学生性别:")
student = Student(id_s, name, age, gender)
Administrator.dict_s[id_s] = student
@staticmethod
def del_message():
id_s = input("请输入你要删除的学生学号:")
# for key in Administrator.dict_s.keys():
if id_s in Administrator.dict_s:
del Administrator.dict_s[id_s]
print("删除成功!!!")
else:
print("抱歉!!该学生信息没找到!!!")
@staticmethod
def update_message():
id_s = input("请输入要改写的学生ID:")
if id_s in Administrator.dict_s:
name = input("请重新输入学生名字:")
age = input("请重新输入学生年龄:")
gender = input("请重新输入学生性别:")
student_new = Student(id_s, name, age, gender)
Administrator.dict_s[id_s] = student_new
else:
print("输入的学号有误!!!")
@staticmethod
def find_message():
id_s = input("请输入你要查找的学生学号:")
if id_s in Administrator.dict_s:
print(Administrator.dict_s[id_s])
else:
print("该学生学号不存在!!!")
@staticmethod
def display_all():
for value in Administrator.dict_s.values():
print(value)
@staticmethod
def file_write():
with open(Administrator.file, "w+", encoding='utf-8') as f:
for value in Administrator.dict_s.values():
# 对象可以直接转换成字符串
f.write(str(value))
f.write('\n')
# Administrator.dict_s.clear()
f.close()
@staticmethod
def menu_sms():
print("----------------------欢迎使用学生管理系统------------------------------------")
print("1.添加学生信息")
print("2.删除学生信息")
print("3.更新学生信息")
print("4.查找学生信息")
print("5.查看所有学生信息")
print("6.从文件中读出学生信息(这个功能不用)")
print("7.保存学生信息到文件到文件")
print("8.退出系统")
print("---------------------------------------------------------------------------")
def start_sms(self):
if os.path.exists("file_message"):
print("正在读....")
with open(Administrator.file, "r+", encoding='utf-8') as f:
for line in f.readlines():
list_s = line.split("\t")
# print(list_s) ['2019401193', '李四', '22', '男\n']
# 回车不放进去
student_s = Student(list_s[0], list_s[1], list_s[2], list_s[3][0:-1])
Administrator.dict_s[list_s[0]] = student_s
else:
print("文件不存在!!!")
while True:
self.menu_sms()
n = int(input("请输入要进行操作的编号:"))
if n == 1:
self.add_message()
elif n == 2:
self.del_message()
elif n == 3:
self.update_message()
elif n == 4:
self.find_message()
elif n == 5:
self.display_all()
elif n == 6:
self.file_read()
elif n == 7:
self.file_write()
elif n == 8:
break
else:
print("输入的编号有误!!!")
teacher = Administrator()
teacher.start_sms()