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

Python读取CSV文件统计薪资时出现ValueError错误该如何解决

问题排查与修复方案

错误原因

你遇到的ValueError核心问题是读取CSV文件时没有跳过表头行:
employeeData.csv第一行是字段名(ename、job、salary、comm、dno),你直接把表头行也放入了数据列表转成字典,导致表头行对应的salary字段取到了非数值内容,甚至因为列错位取到了岗位名SECRETARY,转整型直接失败。
同时你的代码还有两处隐藏bug:

  • D1计算总收入的逻辑错误:int(li['salary']+li['comm'])是先把两个字符串拼接再转整型,比如salary为'2000'、comm为'300'时会拼成'2000300'再转,完全不符合计算要求,应该分别转整型再相加。
  • 没有处理空的comm字段:如果员工无提成comm为空,直接转int会触发报错,需要补充空值判断逻辑。

修复后完整代码

import csv
# 用with语句打开文件,可自动关闭文件避免资源泄漏
with open("employeeData.csv", 'r', encoding='utf-8') as f:
    reader = csv.reader(f)
    # 跳过表头行,符合需求a14行数据的要求
    next(reader)
    emps = list(reader)

dict_of_emp = []
for row in emps:
    d = {}
    d['ename'] = row[0].strip()
    d['job'] = row[1].strip()
    # 提前转数值类型,避免后续重复转换
    d['salary'] = int(row[2].strip())
    # 处理空提成,空值按0计算
    comm_str = row[3].strip()
    d['comm'] = int(comm_str) if comm_str else 0
    d['dno'] = row[4].strip()
    dict_of_emp.append(d)

print("*************************************************")
# 逐行打印员工字典
for emp in dict_of_emp:
    print(emp)

print("*************************************************")
# D1 计算Richard和Mary的总收入
target_emp = ['RICHARD', 'MARY']
for emp in dict_of_emp:
    if emp['ename'] in target_emp:
        total_income = emp['salary'] + emp['comm']
        print(f'income of {emp["ename"]} is {total_income}')

print("*************************************************")
# D2 统计各岗位总薪资
job_salary_total = {}
for emp in dict_of_emp:
    if emp['job'] in job_salary_total:
        job_salary_total[emp['job']] += emp['salary']
    else:
        job_salary_total[emp['job']] = emp['salary']
# 按要求格式输出
for job, total in job_salary_total.items():
    print(f"{job}总薪资为 {total}")

print("*************************************************")
# D3 部门30员工薪资加5000
for emp in dict_of_emp:
    if emp['dno'] == '30':
        emp['salary'] += 5000
# 打印更新后的员工表
for emp in dict_of_emp:
    print(emp)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 00:45:09