Python脚本调用pickle.load触发EOFError错误,寻求解决方法
问题
运行Python脚本的addEmployee()方法录入员工信息时,提交信息后触发EOFError错误,无法正常添加员工。
错误信息
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()
解决方案
1. 修复EOFError问题
空文件无法被pickle.load()读取,会抛出EOFError。需要在读取文件时捕获异常,初始化空列表:
# 修改addEmployee()中的读取部分 try: with open("employees.txt", "rb") as f: employees = pickle.load(f) except (FileNotFoundError, EOFError): employees = []
同理,displayEmployees()、deleteEmployee()、updateEmployee()方法的文件读取部分都需要做相同修改,避免后续操作触发同类错误。
2. 修复员工ID存在性判断错误
原代码直接用employeeID in employees判断是错误的,因为employees是存储字典的列表,不是以ID为键的字典。需要遍历列表检查ID:
# 替换addEmployee()中的判断逻辑 employee_exists = any(emp["employeeID"] == employeeID for emp in employees) if employee_exists: print("Employee with ID {} already exists.".format(employeeID)) return
deleteEmployee()和updateEmployee()中的ID判断逻辑也要同步修改。
3. 修复删除员工逻辑错误
原代码用employees.remove({"employeeID": employeeID})无法删除目标员工,因为新创建的字典和列表中的字典不是同一个对象。需要先找到目标字典再删除:
# 替换deleteEmployee()中的删除代码 for emp in employees: if emp["employeeID"] == employeeID: employees.remove(emp) break
4. 完善updateEmployee方法(可选)
原方法未完成,补充更新薪资或部门的逻辑:
def updateEmployee(): employeeID = int(input("Enter employee ID to update: ")) try: with open("employees.txt", "rb") as f: employees = pickle.load(f) except (FileNotFoundError, EOFError): employees = [] employee = next((emp for emp in employees if emp["employeeID"] == employeeID), None) if not employee: print("Employee with ID {} does not exist.".format(employeeID)) return print("What do you want to update?") print("1. Salary") print("2. Department") ch = int(input("Enter choice: ")) if ch == 1: new_salary = int(input("Enter new annual salary: ")) if 30000 <= new_salary <= 200000: employee["salary"] = new_salary else: print("Salary should be in the range of 30000 and 200000.") return elif ch == 2: new_dept = input("Enter new department: ") if new_dept in ["Marketing", "Finance", "Human Resource", "Technical"]: employee["department"] = new_dept else: print("Department should be Marketing, Finance, Human Resource, or Technical.") return else: print("Invalid choice.") return with open("employees.txt", "wb") as f: pickle.dump(employees, f) print("Employee updated successfully.")
内容的提问来源于stack exchange,提问作者AmmarAli
相关产品推荐
相关产品推荐

