首页 > 解决方案 > 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 新手并且不完全理解所有概念

标签: python

解决方案


每次调用 pickle.dump() 时,它都会覆盖现有文件。因此,首先您需要将所有员工存储在一个列表中,然后使用 dump() 将其写入文件。在检索时,您还需要使用 pickle.load() 将文件中的数据加载到列表中。


推荐阅读