我有以下代码:

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中的各个字段,并将“ if”语句中的值以外的值插入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


非常感谢!

最佳答案

您要访问哪个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。

关于python - Python dict元组超出范围,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26056141/

10-12 21:11