TypeError: 'DictWriter' object is not iterable

TypeError: 'DictWriter' object is not iterable

我正在为非营利筹款活动创建一个简短的简单程序,以在客人登记入住时验证票号,以确保没有重复的票被兑换。我在 运行 Python 3.4.3 Windows 10 机器上。程序完成后,它将在筹款活动的 Raspberry Pi 触摸屏上使用。

我尝试了几种不同的方法来构建列表、保存列表并搜索重复项。理想情况下,列表将存储在 CSV 文件中,但纯文本或其他格式也可以。

你能帮我解决回溯错误吗(TypeError: 'DictWriter' object is not iterable)由于循环函数检查票证#'s对照存储在文件中的列表以确保没有重复的票证被救赎了吗?

提前感谢您的帮助!

version = "v1.4"
fname="tickets.csv"
import csv
import datetime
import os.path
print("\nWelcome to TicketCheck", version)
extant = os.path.isfile(fname)
with open(fname, 'a', newline='') as csvfile:
    fieldnames = ['ticketid', 'timestamp']
    ticketwriter = csv.DictWriter(csvfile, fieldnames=fieldnames)
    if extant == False:
        ticketwriter.writeheader()
    while True:
        ticket = ""
        print("Please enter a ticket # to continue or type exit to exit:")
        ticket = str(input())
        if ticket == "":
            continue
        if ticket == "exit":
            break
        print("You entered ticket # %s." % (ticket))
        print("Validating ticket...")
        for row in ticketwriter:
            if row[0] == ticket:
                print("\n\n\n===== ERROR!!! TICKET # %s ALREADY CHECKED IN =====\n\n\n" % (ticket))
                continue
        time = datetime.datetime.now()
        print("Thank you for checking in ticket # %s at %s \n\n\n" % (ticket, time))
        print("Ticket is now validated.")
        ticketwriter.writerow({'ticketid': ticket, 'timestamp': time})
        csvfile.flush()
        continue
csvfile.close()
print("All your work has been saved in %s.\n Thank you for using TicketCheck %s \n" % (fname, version))

csv.DictWriter class 的对象不可迭代, 你不能像字典、列表甚至字符串那样迭代它们,因此你的错误信息。它不存储您之前写入文件的数据,只有您写入的文件存储该数据。

为了实现您的目标,您可以做两件事:每次需要验证新票证时打开您的 CSV 文件,并检查票证号码是否存在,或者 - 因为您使用的票证数量相对较少data - 在内存中存储字典,仅在使用结束时将其写出,并从中检查票证是否有效。

嗯,我想你可能把这件事想得太复杂了!对于这样的事情,真的没有必要去那么麻烦。这是使用字典的好地方,对于只有两个输入的东西,id 和签到时间,您可以轻松地制作一个 .txt 日志。我感觉这可能更符合您的需求。

import time
go = True
while go:
    the_guestlist = {}
    the_ticket = input().strip()
    file = open('somefile.txt', 'r')
    for line in file:
        my_items = line.split(',')
        the_guestlist[my_items[0]] = my_items[1]
    file.close()
    if the_ticket in the_guestlist.keys():
        print("Sorry, that ticket has been entered at {}".format(the_guestlist[the_ticket]))
    elif the_ticket == 'exit':
        go = False
        print('Exiting...')
    else:
        the_guestlist[the_ticket] = '{}'.format(time.asctime())
        file = open('somefile.txt', 'a')
        file.write(the_ticket +','+the_guestlist[the_ticket]+'\n')
        file.close()