还要学生的存储信息文件
时间: 2023-12-03 11:04:22 浏览: 17
好的,根据你的需求,我们可以使用CSV文件来存储学生的信息。下面是修改后的代码示例:
```python
import datetime
import csv
class ComputerRoom:
def __init__(self):
self.students = {}
self.load_students()
def add_student(self, id, name, cls, start_time):
self.students[id] = {'name': name, 'class': cls, 'start_time': start_time}
self.save_students()
def end_session(self, id):
start_time = self.students[id]['start_time']
end_time = datetime.datetime.now()
duration = end_time - start_time
hours = duration.total_seconds() / 3600
if hours < 0.5:
cost = 1.0
elif hours < 1:
cost = 2.0
elif hours < 3:
cost = 2.0 * hours
else:
cost = 6.0 + (hours - 3) * 3.0
print(f"{self.students[id]['name']}上机时长为{hours:.2f}小时,费用为{cost:.2f}元")
del self.students[id]
self.save_students()
def query_student(self, id=None, name=None):
if id:
if id in self.students:
print(f"{self.students[id]['name']}的上机时间为{self.students[id]['start_time']}")
else:
print(f"学号为{id}的学生未找到")
elif name:
found = False
for id, student in self.students.items():
if student['name'] == name:
print(f"{student['name']}的上机时间为{student['start_time']}")
found = True
if not found:
print(f"姓名为{name}的学生未找到")
def check_duration(self, id):
start_time = self.students[id]['start_time']
end_time = datetime.datetime.now()
duration = end_time - start_time
hours = duration.total_seconds() / 3600
if hours > 5:
print(f"{self.students[id]['name']}已连续上机超过5小时,请注意休息!")
def load_students(self):
try:
with open('students.csv', newline='') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
id, name, cls, start_time = row
start_time = datetime.datetime.fromisoformat(start_time)
self.students[id] = {'name': name, 'class': cls, 'start_time': start_time}
except FileNotFoundError:
pass
def save_students(self):
with open('students.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
for id, student in self.students.items():
writer.writerow([id, student['name'], student['class'], student['start_time'].isoformat()])
def run(self):
while True:
print("1. 输入学生信息")
print("2. 结束上机")
print("3. 查询学生信息")
choice = input("请选择操作:")
if choice == '1':
id = input("请输入学生学号:")
name = input("请输入学生姓名:")
cls = input("请输入学生班级:")
start_time = datetime.datetime.now()
self.add_student(id, name, cls, start_time)
print(f"{name}已成功登录计算机房,上机时间为{start_time}")
elif choice == '2':
id = input("请输入学生学号:")
self.end_session(id)
elif choice == '3':
id = input("请输入学生学号(留空则按姓名查询):")
if id:
self.query_student(id=id)
else:
name = input("请输入学生姓名:")
self.query_student(name=name)
else:
print("输入错误,请重新选择!")
continue
for id in self.students:
self.check_duration(id)
```
在新的代码中,我们添加了`load_students`和`save_students`两个方法,用来读取和保存CSV文件。在程序启动时,会自动读取CSV文件中的学生信息,而在添加或结束上机时,会自动保存学生信息到CSV文件中。
注意,CSV文件中的时间是使用ISO格式存储的,可以使用`datetime.datetime.fromisoformat`方法将其转换为`datetime.datetime`类型。