这个脚本工作正常,直到我点击一个空的单元格:
import csv,time,string,os,requests
dw = "\\\\network\\folder\\btc.csv"
inv_fields = ["id", "rsl", "number", "GP%"]
with open(dw) as infile, open("c:\\upload\\log.csv", "wb") as outfile:
r = csv.DictReader(infile)
w = csv.DictWriter(outfile, inv_fields, extrasaction="ignore")
r = (dict((k, v.strip()) for k, v in row.items() if v) for row in r)
wtr = csv.writer( outfile )
wtr.writerow(["id", "resale", "number", "percentage"])
for i, row in enumerate(r, start=1):
row['id'] = i
row['GP%'] = row['GP%'].replace("%","")
w.writerow(row)
print "file successfully saved"
脚本在此行上失败:
row['GP%'] = row['GP%'].replace("%","")
并且通过将print i
添加到循环中,我可以看到它在.csv文件的行上失败,其中此输入值为空。如何将没有值的单元格纳入此等式?
python错误:
Traceback (most recent call last):
File "backlog.py", line 80, in <module>
row['GP%'] = row['GP%'].replace("%","")
KeyError: 'GP%'
答案 0 :(得分:1)
在尝试更新其值之前,您可以检查密钥'GP%'
是否在row
字典中。如果不是,您可以分配默认值,以便输出文件中与id
相关的条目为空:
for i, row in enumerate(r, start=1):
row['id'] = i
if 'GP%' in row:
row['GP%'] = row['GP%'].replace('%','')
else:
row['GP%'] = ''
w.writerow(row)
或使用get
row
方法设置默认值:
for i, row in enumerate(r, start=1):
row['id'] = i
row['GP%'] = row.get('GP%', '').replace('%','')
w.writerow(row)
答案 1 :(得分:1)
您可以使用"GP%" in row
检查行中是否存在GP%
。
或者,您可以捕获异常:
try:
row['GP%'] = row['GP%'].replace("%","")
except KeyError as ke:
print "Error:{0}, row info:{1}".format(ke, row)