【发布时间】:2021-12-19 23:57:52
【问题描述】:
我正在开发一个程序,该程序应该根据年龄将员工工资更新 %5 和 %10:
import csv
infile = open('employee.csv')
csvreader = csv.reader(infile)
rows = []
for row in csvreader:
rows.append(row)
for i in rows:
if(int(i[2]) < 40): #LINE CAUSING A PROBLEM
i[3] = round((1.05 * float(i[3])) , 2)
else:
i[3] = round((1.10 * float(i[3])) , 2)
print('\n\nList after updation:')
#loop print the data on the compile
for row in rows:
print(row)
#open file and write the updated data
with open('employeeUpdate.csv', 'w', encoding='UTF8', newline='') as f:
writer = csv.writer(f)
for row in rows:
writer.writerow(row)
当我运行它时,我收到以下错误:
ValueError Traceback (most recent call last)
---> 23 if(int(i[2]) < 40):
ValueError: invalid literal for int() with base 10: 'age'
数据样本:
ID employee name age salary
1 Sara Wales 33 60994
2 John Smith 42 78399
3 Michael Ousley 22 58000
4 Rami Elliot 50 88382
我仔细检查了数据类型,它是一个整数-->('age', dtype('int64'))
我尝试了with open ('employee.csv', r) as infile 并将问题行更改为if int(float(i[2]) < 40):,但它们都不起作用。
它说不能将字符串转换为浮点数。我不知道它为什么将整数读取为字符串。
但是当我添加这样的异常时:
for i in rows:
try:
if (int(i[2]) < 40):
i[3] = round((1.05 * int(i[3])) , 2)
else:
i[3] = round((1.10 * int(i[3])) , 2)
except ValueError:
print("")
它有效,所以我的问题是为什么它只在例外情况下有效!有没有办法在没有例外的情况下完成它?
【问题讨论】:
-
从错误看来您在 i[2] 处获取字符串,您能否也发布示例输入
-
@RoboC:你有什么理由不考虑使用 pandas 吗?这将使这变得容易得多,您能否发布一个小样本
-
请分享一些关于 employee.csv 的信息,它可能是一些被 try/except 跳过的信息(也许你有标题或其他东西)
-
@Hackaholic 我添加了示例
-
@UGuntupalli 没有不使用熊猫的具体原因,我就是这样做的。我添加了一个 csv 文件的样本
标签: python python-3.x csv valueerror