帮我用python写一个可以将每次增加、删除和修改学生信息后的结果保存至本地文件中,并在程序开启时尝试从本地文件读取学生信息,以便实现程序重启后仍然能够查询原有数据,按学号从小到大输出,学生信息包含有姓名,学号,性别,年龄,手机号,班级,身份证号码,并标注上注释
时间: 2023-06-20 12:08:05 浏览: 81
好的,以下是一个简单的实现方式:
```python
import json
# 文件名
FILENAME = "students.json"
# 学生类
class Student:
def __init__(self, name, id, gender, age, phone, cls, id_card):
self.name = name
self.id = id
self.gender = gender
self.age = age
self.phone = phone
self.cls = cls
self.id_card = id_card
def to_dict(self):
# 将学生对象转为字典
return {
"name": self.name,
"id": self.id,
"gender": self.gender,
"age": self.age,
"phone": self.phone,
"class": self.cls,
"id_card": self.id_card
}
# 学生信息管理类
class StudentManager:
def __init__(self):
self.students = [] # 学生列表
# 尝试从文件中读取学生信息
try:
with open(FILENAME, "r") as f:
data = json.load(f)
for s in data:
student = Student(s["name"], s["id"], s["gender"], s["age"], s["phone"], s["class"], s["id_card"])
self.students.append(student)
except:
pass
def add_student(self, student):
# 添加学生
self.students.append(student)
self.save_to_file()
def remove_student(self, student):
# 删除学生
self.students.remove(student)
self.save_to_file()
def modify_student(self, student, new_info):
# 修改学生信息
student.name = new_info.get("name", student.name)
student.id = new_info.get("id", student.id)
student.gender = new_info.get("gender", student.gender)
student.age = new_info.get("age", student.age)
student.phone = new_info.get("phone", student.phone)
student.cls = new_info.get("cls", student.cls)
student.id_card = new_info.get("id_card", student.id_card)
self.save_to_file()
def save_to_file(self):
# 将学生信息保存到文件中
data = [s.to_dict() for s in self.students]
with open(FILENAME, "w") as f:
json.dump(data, f)
def print_students(self):
# 按学号从小到大输出学生信息
sorted_students = sorted(self.students, key=lambda s: s.id)
for s in sorted_students:
print(s.name, s.id, s.gender, s.age, s.phone, s.cls, s.id_card)
# 测试
if __name__ == "__main__":
sm = StudentManager()
sm.add_student(Student("张三", "1001", "男", 18, "13888888888", "一班", "110101200001011234"))
sm.add_student(Student("李四", "1002", "女", 19, "13999999999", "一班", "110101200002022345"))
sm.print_students()
print()
sm.modify_student(sm.students[0], {"phone": "13666666666"})
sm.remove_student(sm.students[1])
sm.print_students()
```
其中,我们使用了 `json` 模块将学生信息保存到文件中,并在程序启动时尝试从文件中读取数据。同时,我们也实现了添加、删除和修改学生信息的功能。最后,我们按学号从小到大输出学生信息。
阅读全文