You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

员工数据管理系统(EDMS)删除/更新功能报错:EmployeeID不存在

员工数据管理系统(EDMS)删除/更新功能错误修复方案

问题根源分析

你的代码存在两个核心逻辑错误,导致删除和更新时始终提示“EmployeeID不存在”:

  • 存在性判断错误:employeeID in employees 这种写法是判断整数是否直接是列表的元素,但employees存储的是员工字典,整数不可能等于字典,所以这个判断永远为False。
  • 删除操作错误:employees.remove({"employeeID": employeeID}) 创建了一个新字典,和列表中已有的员工字典不是同一个对象,即使ID匹配也无法找到并删除目标元素。

修复后的完整代码

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 not os.path.exists("employees.pkl"):
        employees = []
        with open("employees.pkl", "wb") as f:
            pickle.dump(employees, f)
            
    with open("employees.pkl", "rb") as f:
        employees = pickle.load(f)
        # 修复:遍历字典列表检查ID是否存在
        for emp in employees:
            if emp["employeeID"] == employeeID:
                print("Employee with ID {} 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():
    if not os.path.exists("employees.pkl"):
        print("No employees found.")
        return
        
    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: "))

    if not os.path.exists("employees.pkl"):
        print("Employee with ID {} does not exist.".format(employeeID))
        return
        
    with open("employees.pkl", "rb") as f:
        employees = pickle.load(f)
        # 修复:遍历查找对应ID的员工
        target_emp = None
        for emp in employees:
            if emp["employeeID"] == employeeID:
                target_emp = emp
                break
        if not target_emp:
            print("Employee with ID {} does not exist.".format(employeeID))
            return

    employees.remove(target_emp)

    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: "))

    if not os.path.exists("employees.pkl"):
        print("Employee with ID {} does not exist.".format(employeeID))
        return
        
    with open("employees.pkl", "rb") as f:
        employees = pickle.load(f)
        # 修复:遍历查找对应ID的员工
        target_emp = None
        for emp in employees:
            if emp["employeeID"] == employeeID:
                target_emp = emp
                break
        if not target_emp:
            print("Employee with ID {} does not exist.".format(employeeID))
            return

    print("What do you want to update?")
    print("1 to Update Department")
    print("2 to Update Salary")
    ch = int(input("Enter your choice: "))
    
    if ch == 1:
        new_dept = input("Enter new department: ")
        if new_dept in ["Marketing", "Finance", "Human Resource", "Technical"]:
            target_emp["department"] = new_dept
            print("Department updated successfully.")
        else:
            print("Invalid department.")
            return
    elif ch == 2:
        new_salary = int(input("Enter new annual salary: "))
        if 30000 <= new_salary <= 200000:
            target_emp["salary"] = new_salary
            print("Salary updated successfully.")
        else:
            print("Salary should be in the range of 30000 and 200000.")
            return
    else:
        print("Invalid choice.")
        return

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


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")

    try:
        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()
    except ValueError:
        print("Please enter a valid number.")
        menu()

menu()

关键修复点说明

  1. 存在性判断:将employeeID in employees替换为遍历列表中的每个字典,检查emp["employeeID"] == employeeID,正确判断员工ID是否存在。
  2. 删除操作:先找到目标员工字典对象,再用employees.remove(target_emp)删除,确保操作的是列表中实际存在的元素。
  3. 更新功能补全:完善了updateEmployee函数的逻辑,支持修改部门和薪资,并同步保存到文件。
  4. 边界处理:增加了文件不存在时的判断,避免读取不存在的文件报错。

内容的提问来源于stack exchange,提问作者AmmarAli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 14:34:51