python - Python 只打印最后输入的数据
问题描述
我有一项任务是创建一个包含员工姓名、身份证号码、部门和职位的类。用户应该能够输入多个员工的信息,并在最后打印出所有信息。
我面临的问题是只有最后一个员工的信息被打印出来。
import pickle
import employee
data = 'data.dat'
def main():
output_file = open(data, 'wb')
end_of_file = False
keep_going = 'Y'
while keep_going == 'Y':
name = str(input('Name of employee: '))
ID_num = int(input('Employee ID number: '))
dep = str(input('Department: '))
job = str(input('Job Title: '))
emp = employee.Employee(name, ID_num)
emp.set_department(dep)
emp.set_job_title(job)
pickle.dump(emp, output_file)
keep_going = input('Enter another employee file? (Use Y / N): ')
input_file = open(data, 'rb')
while not end_of_file:
try:
emp = pickle.load(input_file)
display_data(emp)
except EOFError:
end_of_file = True
input_file.close()
if keep_going == 'N':
print(display_data(emp))
output_file.close()
def display_data(emp):
print('Name','\t','\t','ID Number','\t','Department','\t','\t','Job Title')
print(emp.get_name(), '\t', emp.get_ID_num(),'\t','\t',emp.get_department(),'\t','\t',emp.get_job_title())
main()
如果有人知道为什么会发生这种情况并对如何解决它有任何建议,我将非常感激,因为我是 python 新手并且不完全理解所有概念
解决方案
每次调用 pickle.dump() 时,它都会覆盖现有文件。因此,首先您需要将所有员工存储在一个列表中,然后使用 dump() 将其写入文件。在检索时,您还需要使用 pickle.load() 将文件中的数据加载到列表中。
推荐阅读
- node.js - 在添加字段之前发送 Node.js 嵌入,如何确保在使用 Discord.js 发送嵌入之前完全构建嵌入
- tcp - Winsock发送多个数据包api?
- regex - 如何使用正则表达式过滤 Kotlin 中的列表
- c# - Asp.net WebForms 中继器 OnClick 在中继器内时未触发
- python-3.x - 使用 Cygwin 在 Windows 上安装 uWSGI 失败
- pyspark - 使用 pyspark 将 Json 数据加载到 hbase
- javascript - 来自 Bootstrapious 联系表单的成功消息显示在空白页面上
- php - 用数组填充表格
- excel - ssrs 以 csv 格式导出到 excel
- angular - 将 *ngFor 与迭代器一起使用的正确方法是什么?