`pickle.load` 抛出 `EOFError: Ran out of input` 错误

问题描述 投票:0回答:1

我编写了这个 python 脚本,每次运行它时,它都应该输入一些必须在

addEmployee()
方法中接受的详细信息。当我按 Enter 提交所有信息时,它会抛出以下错误:

Traceback (most recent call last):
  File "C:\Users\ammar\PycharmProjects\pythonProject\main.py", line 122, in <module>
    menu()
  File "C:\Users\ammar\PycharmProjects\pythonProject\main.py", line 108, in menu
    addEmployee()
  File "C:\Users\ammar\PycharmProjects\pythonProject\main.py", line 35, in addEmployee
    employees = pickle.load(f)
                ^^^^^^^^^^^^^^
EOFError: Ran out of input

Process finished with exit code 1

其他信息:我正在使用 Pycharm 来执行此操作,并且我在存储该程序的同一文件夹中制作了一个名为

employees.txt
的文本文件

我不知道如何解决这个问题,我们将不胜感激。

这是我的脚本:
import datetime
import pickle

def addEmployee():
    fullName = input("Enter full name: ")
    employeeID = int(input("Enter employee ID: "))
    department = input("Enter department: ")
    doj = input("Enter date of joining (MM/DD/YYYY): ")
    salary = int(input("Enter annual salary: "))

    if len(fullName) == 0:
        print("Please enter full name.")
        return

    if not 10000 <= employeeID <= 99999:
        print("Employee ID should be in the range of 10000 and 99999.")
        return

    if department not in ["Marketing", "Finance", "Human Resource", "Technical"]:
        print("Department should be Marketing, Finance, Human Resource, or Technical.")
        return

    try:
        datetime.datetime.strptime(doj, "%m/%d/%Y")
    except ValueError:
        print("Invalid date of joining format.")
        return

    if not 30000 <= salary <= 200000:
        print("Salary should be in the range of 30000 and 200000.")
        return

    with open("employees.txt", "rb") as f:
        employees = pickle.load(f)
        if employeeID in employees:
            print("Employee with ID {} already exists.".format(employeeID))
            return

    employees.append({
        "fullName": fullName,
        "employeeID": employeeID,
        "department": department,
        "doj": doj,
        "salary": salary
    })

    with open("employees.txt", "wb") as f:
        pickle.dump(employees, f)

    print("Employee added successfully.")


def displayEmployees():
    with open("employees.txt", "rb") as f:
        employees = pickle.load(f)

    if len(employees) == 0:
        print("No employees found.")
        return

    print("Employees:")
    for employee in employees:
        print(employee)


def deleteEmployee():
    employeeID = int(input("Enter employee ID to delete: "))

    with open("employees.txt", "rb") as f:
        employees = pickle.load(f)
        if employeeID not in employees:
            print("Employee with ID {} does not exist.".format(employeeID))
            return

    employees.remove({"employeeID": employeeID})

    with open("employees.txt", "wb") as f:
        pickle.dump(employees, f)

    print("Employee deleted successfully.")


def updateEmployee():
    employeeID = int(input("Enter employee ID to update: "))

    with open("employees.txt", "rb") as f:
        employees = pickle.load(f)
        if employeeID not in employees:
            print("Employee with ID {} does not exist.".format(employeeID))
            return

    updatedSalary = None
    updatedDepartment = None

    print("What do you want to update?")


def menu():
    print("1 to Add Employee")
    print("2 to Delete Employee")
    print("3 to Update Employee")
    print("4 to Display Employees")
    print("5 to Exit")

    ch = int(input("Enter your Choice:"))
    if ch == 1:
        addEmployee()
    elif ch == 2:
        deleteEmployee()
    elif ch == 3:
        updateEmployee()
    elif ch == 4:
        displayEmployees()
    elif ch == 5:
        exit(0)
    else:
        print("Invalid Input")
        menu()


menu()

提前致谢!

python python-3.x pickle eoferror
1个回答
1
投票

您面临

EOFError: Ran out of input
错误,因为您尝试将通用
.txt
文件作为
.pkl
对象加载。文件名应为
employees.pkl
。这是您更正后的代码:

import datetime
import pickle
import os

def addEmployee():
    fullName = input("Enter full name: ")
    employeeID = int(input("Enter employee ID: "))
    department = input("Enter department: ")
    doj = input("Enter date of joining (MM/DD/YYYY): ")
    salary = int(input("Enter annual salary: "))

    if len(fullName) == 0:
        print("Please enter full name.")
        return

    if not 10000 <= employeeID <= 99999:
        print("Employee ID should be in the range of 10000 and 99999.")
        return

    if department not in ["Marketing", "Finance", "Human Resource", "Technical"]:
        print("Department should be Marketing, Finance, Human Resource, or Technical.")
        return

    try:
        datetime.datetime.strptime(doj, "%m/%d/%Y")
    except ValueError:
        print("Invalid date of joining format.")
        return

    if not 30000 <= salary <= 200000:
        print("Salary should be in the range of 30000 and 200000.")
        return
    
    if os.path.exists("employees.pkl") == False:
        employees = []
        with open("employees.pkl", "wb") as f:
            pickle.dump(employees, f)
            
    with open("employees.pkl", "rb") as f:
        employees = pickle.load(f)
        if employeeID in employees:
            print("Employee with ID1 {} already exists.".format(employeeID))
            return

    employees.append({
        "fullName": fullName,
        "employeeID": employeeID,
        "department": department,
        "doj": doj,
        "salary": salary
    })

    with open("employees.pkl", "wb") as f:
        pickle.dump(employees, f)

    print("Employee added successfully.")


def displayEmployees():
    with open("employees.pkl", "rb") as f:
        employees = pickle.load(f)

    if len(employees) == 0:
        print("No employees found.")
        return

    print("Employees:")
    for employee in employees:
        print(employee)


def deleteEmployee():
    employeeID = int(input("Enter employee ID to delete: "))

    with open("employees.pkl", "rb") as f:
        employees = pickle.load(f)
        if employeeID not in employees:
            print("Employee with ID {} does not exist.".format(employeeID))
            return

    employees.remove({"employeeID": employeeID})

    with open("employees.pkl", "wb") as f:
        pickle.dump(employees, f)

    print("Employee deleted successfully.")


def updateEmployee():
    employeeID = int(input("Enter employee ID to update: "))

    with open("employees.pkl", "rb") as f:
        employees = pickle.load(f)
        if employeeID not in employees:
            print("Employee with ID {} does not exist.".format(employeeID))
            return

    updatedSalary = None
    updatedDepartment = None

    print("What do you want to update?")


def menu():
    print("1 to Add Employee")
    print("2 to Delete Employee")
    print("3 to Update Employee")
    print("4 to Display Employees")
    print("5 to Exit")

    ch = int(input("Enter your Choice:"))
    if ch == 1:
        addEmployee()
    elif ch == 2:
        deleteEmployee()
    elif ch == 3:
        updateEmployee()
    elif ch == 4:
        displayEmployees()
    elif ch == 5:
        exit(0)
    else:
        print("Invalid Input")
        menu()
menu()

输出:

1 to Add Employee
2 to Delete Employee
3 to Update Employee
4 to Display Employees
5 to Exit
Enter your Choice:1
Enter full name: rafi
Enter employee ID: 10001
Enter department: Technical
Enter date of joining (MM/DD/YYYY): 12/12/1998
Enter annual salary: 40001
Employee added successfully.

此外,我对代码做了一些修改。第一次运行代码时,您不必手动创建

.pkl
文件。当您第一次运行脚本时,此代码块将创建一个空的 pickle 文件。从那时起,新条目将保存到此“employees.pkl”文件中。

if os.path.exists("employees.pkl") == False:
    employees = []
    with open("employees.pkl", "wb") as f:
        pickle.dump(employees, f)
© www.soinside.com 2019 - 2024. All rights reserved.