gpt4 book ai didi

python - 类型错误 : 'DictWriter' object is not iterable

转载 作者:行者123 更新时间:2023-11-28 21:42:42 25 4
gpt4 key购买 nike

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

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

你能帮我解决回溯错误吗(TypeError: 'DictWriter' object is not iterable),这是由于循环函数根据存储在文件中的列表检查票证 # 以确保没有重复的票证被兑换?

预先感谢您的帮助!

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))

最佳答案

嗯,我想你可能把这件事复杂化了一点!对于这样的事情,真的没有必要去那么麻烦。这是使用字典的好地方,对于只有两个输入的东西,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()

关于python - 类型错误 : 'DictWriter' object is not iterable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43290647/

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