我有这段代码:
f = open('File4Gym.dat')
try:
db = lite.connect('/var/www/members.db')
fieldnames = ('Shop', 'PUC Code Num', 'Name', 'Date/ Reason', 'Amount', 'T', 'PUC Code', 'Status', 'Date')
reader = csv.DictReader(f, fieldnames=fieldnames)
for row in reader:
for fieldnames in row.items():
#print row
if fieldnames[5] <> '0.00' or '14.95' or '16.95':
print "Committing INSERT"
c = db.execute("""INSERT "debit" = '%s' FROM "members" WHERE "puccode" = '%s'""" % (fieldnames[5], fieldnames[7],))
返回错误:
pi@raspberrypi ~ $ python cronjob3.py
Traceback (most recent call last):
File "cronjob3.py", line 13, in <module>
if fieldnames[5] <> '0.00' or '14.95' or '16.95':
IndexError: tuple index out of range
我如何引用csv.DictReader中的各个字段并插入除&#34之外的值;如果&#34;声明进入SQL表?
示例文件(根据要求提供):
"Shop Name",PUCLxxx,"Customer 1","09/09/2014",0.00,T,"PUCLxxx","Closed Account ",20140909
"Shop Name",PUCLyyy,"Customer 2","09/09/2014",0.00,T,"PUCLyyy","Closed Account ",20140909
非常感谢!
答案 0 :(得分:1)
您想要访问哪个fieldnames
?您将其定义为('Shop', 'PUC...
,然后使用for fieldnames in row:
。我想其中一个需要重命名。
新fieldnames
必须短于6个元素。尝试在循环中打印出来以查看返回的内容。
编辑:我想我发现了这个问题。
您for fieldnames in row.items():
fieldnames
对字典row
中的键/值对进行迭代的位置。每对都是一个2元组,所以5个超出范围。
我认为用以下内容替换你的for
循环应该做你想要实现的目标
for row in reader:
if row['Amount'] <> '0.00' or '14.95' or '16.95': #is this the field you were after?
print "Committing INSERT"
c = db.execute("""INSERT "debit" = '%s' FROM "members" WHERE "puccode" = '%s'""" % (row['Amount'], row['PUC Code Num'],))
作为旁注,您希望在if row['Amount'] <> '0.00' or '14.95' or '16.95':
条件下实现什么目标?正如它所写,它将永远是真的。如果您想检查金额是不是0.00或14.95或16.95之一,请使用if row['Amount'] not in ('0.00', '14.95', '16.95'):
PS:fieldnames [5]会返回'T'而不是'Amount',因为列表是0索引。