编写一个“学生信息管理系统”的代码,实现增显示所有学生信息,新建学生信息,查询学生信息,修改学生信息,删除学生信息,保存学生信息,恢复学生信息等功能
时间: 2024-03-24 19:41:47 浏览: 50
好的,以下是一个 Python 版本的学生信息管理系统代码示例,可以根据你的需求进行修改:
```python
import os
import pickle
class Student:
def __init__(self, id, name, age, gender):
self.id = id
self.name = name
self.age = age
self.gender = gender
class StudentManager:
def __init__(self):
self.students = []
self.load_data()
def load_data(self):
if os.path.exists('students.dat'):
with open('students.dat', 'rb') as f:
self.students = pickle.load(f)
def save_data(self):
with open('students.dat', 'wb') as f:
pickle.dump(self.students, f)
def add_student(self):
id = input('请输入学号:')
name = input('请输入姓名:')
age = input('请输入年龄:')
gender = input('请输入性别:')
student = Student(id, name, age, gender)
self.students.append(student)
print('添加成功!')
def show_students(self):
for student in self.students:
print('学号:{},姓名:{},年龄:{},性别:{}'.format(student.id, student.name, student.age, student.gender))
def find_student(self):
id = input('请输入要查询的学号:')
for student in self.students:
if student.id == id:
print('学号:{},姓名:{},年龄:{},性别:{}'.format(student.id, student.name, student.age, student.gender))
return
print('未找到该学生!')
def modify_student(self):
id = input('请输入要修改的学号:')
for student in self.students:
if student.id == id:
name = input('请输入姓名(回车不修改):')
if name != '':
student.name = name
age = input('请输入年龄(回车不修改):')
if age != '':
student.age = age
gender = input('请输入性别(回车不修改):')
if gender != '':
student.gender = gender
print('修改成功!')
return
print('未找到该学生!')
def delete_student(self):
id = input('请输入要删除的学号:')
for student in self.students:
if student.id == id:
self.students.remove(student)
print('删除成功!')
return
print('未找到该学生!')
def backup_data(self):
os.rename('students.dat', 'students.dat.bak')
print('备份成功!')
def restore_data(self):
if os.path.exists('students.dat.bak'):
os.remove('students.dat')
os.rename('students.dat.bak', 'students.dat')
print('恢复成功!')
else:
print('未找到备份文件!')
def run(self):
while True:
print('1. 显示所有学生信息')
print('2. 新建学生信息')
print('3. 查询学生信息')
print('4. 修改学生信息')
print('5. 删除学生信息')
print('6. 保存学生信息')
print('7. 备份学生信息')
print('8. 恢复学生信息')
print('9. 退出程序')
choice = input('请选择操作:')
if choice == '1':
self.show_students()
elif choice == '2':
self.add_student()
elif choice == '3':
self.find_student()
elif choice == '4':
self.modify_student()
elif choice == '5':
self.delete_student()
elif choice == '6':
self.save_data()
print('保存成功!')
elif choice == '7':
self.backup_data()
elif choice == '8':
self.restore_data()
elif choice == '9':
break
else:
print('输入有误,请重新选择!')
if __name__ == '__main__':
manager = StudentManager()
manager.run()
```
这个示例代码实现了增显示所有学生信息,新建学生信息,查询学生信息,修改学生信息,删除学生信息,保存学生信息,恢复学生信息等功能。其中,学生信息以类的形式存储,通过 pickle 模块进行数据的读写和备份恢复。你可以根据自己的需求来进行修改和扩展。
阅读全文