定义一个 Student 类,其中包含学号、姓名、成绩数据成员。建立若干个 Student 类 对象,将它们保存到文件 Record.dat 中,然后显示文件中的内容。
时间: 2024-02-22 07:55:28 浏览: 21
好的,以下是实现该问题的Python代码:
```python
import pickle
class Student:
def __init__(self, num, name, score):
self.num = num
self.name = name
self.score = score
# 创建若干个 Student 对象
students = [Student("001", "张三", 90), Student("002", "李四", 80), Student("003", "王五", 70)]
# 将 Student 对象保存到文件 Record.dat 中
with open("Record.dat", "wb") as f:
for s in students:
pickle.dump(s, f)
# 从文件 Record.dat 中读取 Student 对象并显示
with open("Record.dat", "rb") as f:
while True:
try:
s = pickle.load(f)
print("学号:{},姓名:{},成绩:{}".format(s.num, s.name, s.score))
except EOFError:
break
```
代码说明:
1. 定义了一个 Student 类,包含学号、姓名、成绩数据成员。
2. 创建了三个 Student 类对象,并保存到文件 Record.dat 中,使用 pickle 模块的 dump() 函数实现。
3. 从文件 Record.dat 中读取 Student 对象并显示,使用 pickle 模块的 load() 函数实现。由于不知道文件中 Student 对象的数量,因此使用 while 循环和 try-except 语句读取文件中的所有对象。当读到文件结尾时,会触发 EOFError 异常,此时跳出循环。