gpt4 book ai didi

python 处理 DictReader 缺少键

转载 作者:行者123 更新时间:2023-12-01 03:50:10 26 4
gpt4 key购买 nike

这个脚本工作正常,直到我点击一个空的单元格:

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 文件的该输入值为空的行上失败。如何将没有值(value)的单元格带入这个方程?

Python 错误:

Traceback (most recent call last):
File "backlog.py", line 80, in <module>
row['GP%'] = row['GP%'].replace("%","")
KeyError: 'GP%'

最佳答案

在尝试更新其值之前,您可以检查键 '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)

或者使用rowget方法设置默认值:

for i, row in enumerate(r, start=1):
row['id'] = i
row['GP%'] = row.get('GP%', '').replace('%','')
w.writerow(row)

关于python 处理 DictReader 缺少键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38383680/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com