Files
AI0814_jiaoan_public/w0_d6/06_students_persistence_json.py
T
2026-09-21 17:11:35 +08:00

173 lines
4.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
06 数据持久化版本:学生增删改查
持久化:
程序运行时,数据在内存里。
程序结束后,内存数据会消失。
如果希望下次打开程序还能看到数据,就要把数据保存到文件或数据库。
本文件使用 JSON 文件保存数据。
运行后会在当前目录生成 students.json。
"""
import json
from pathlib import Path
DATA_FILE = Path("students.json")
class Student:
def __init__(self, student_id, name, age, phone):
self.id = student_id
self.name = name
self.age = age
self.phone = phone
def to_dict(self):
return {
"id": self.id,
"name": self.name,
"age": self.age,
"phone": self.phone,
}
@classmethod
def from_dict(cls, data):
return cls(
data["id"],
data["name"],
data["age"],
data["phone"],
)
def __str__(self):
return f"ID: {self.id}, 姓名: {self.name}, 年龄: {self.age}, 电话: {self.phone}"
class StudentManager:
def __init__(self):
self.students = []
self.next_id = 1
self.load()
def load(self):
if not DATA_FILE.exists():
return
with DATA_FILE.open("r", encoding="utf-8") as file:
data = json.load(file)
self.next_id = data.get("next_id", 1)
self.students = [
Student.from_dict(item)
for item in data.get("students", [])
]
def save(self):
data = {
"next_id": self.next_id,
"students": [student.to_dict() for student in self.students],
}
with DATA_FILE.open("w", encoding="utf-8") as file:
json.dump(data, file, ensure_ascii=False, indent=2)
def add_student(self):
name = input("姓名:").strip()
age = input("年龄:").strip()
phone = input("电话:").strip()
self.students.append(Student(self.next_id, name, age, phone))
self.next_id += 1
self.save()
print("添加成功")
def list_students(self):
if not self.students:
print("暂无学生")
return
for student in self.students:
print(student)
def find_student_by_id(self, student_id):
for student in self.students:
if str(student.id) == str(student_id):
return student
return None
def search_student(self):
keyword = input("请输入要查询的姓名:").strip()
result = [student for student in self.students if student.name == keyword]
if not result:
print("没有找到该学生")
return
for student in result:
print(student)
def update_student(self):
student_id = input("请输入要修改的学生 ID:").strip()
student = self.find_student_by_id(student_id)
if student is None:
print("没有找到该学生")
return
student.name = input("新姓名:").strip()
student.age = input("新年龄:").strip()
student.phone = input("新电话:").strip()
self.save()
print("修改成功")
def delete_student(self):
student_id = input("请输入要删除的学生 ID:").strip()
student = self.find_student_by_id(student_id)
if student is None:
print("没有找到该学生")
return
self.students.remove(student)
self.save()
print("删除成功")
class Application:
def __init__(self):
self.manager = StudentManager()
self.menu = {
"1": ("添加学生", "add_student"),
"2": ("查看所有学生", "list_students"),
"3": ("查询学生", "search_student"),
"4": ("修改学生", "update_student"),
"5": ("删除学生", "delete_student"),
}
def show_menu(self):
print("\n====== 学生管理系统:JSON 持久化版本 ======")
for key, value in self.menu.items():
title, _ = value
print(f"{key}. {title}")
print("0. 退出")
def run(self):
while True:
self.show_menu()
choice = input("请输入操作编号:").strip()
if choice == "0":
print("程序结束")
break
if choice not in self.menu:
print("输入有误,请重新输入")
continue
_, method_name = self.menu[choice]
getattr(self.manager, method_name)()
if __name__ == "__main__":
app = Application()
app.run()