我正在努力为非营利组织筹款人创建一个简短的简单程序,以便在客人办理登机手续时验证机票号码,以确保不会兑换重复的机票。我在Windows 10机器上运行Python 3.4.3。一旦程序完成,它将用于筹款活动的带有触摸屏的Raspberry Pi。
我尝试了几种不同的方法来构建列表,保存并搜索重复项。理想情况下,列表将存储在CSV文件中,但纯文本或其他格式也可以。
你可以帮我解决回溯错误(TypeError:'DictWriter'对象不可迭代),因为循环函数根据存储在文件中的列表检查票证#以确保没有重复的票据被兑换?
提前感谢您的帮助!
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))
答案 0 :(得分:5)
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()
答案 1 :(得分:0)
csv.DictWriter
类的对象不可迭代,即你不能像字典,列表甚至字符串那样迭代它们,因此你的错误信息。它不存储您先前写入文件的数据,只存储您编写的文件以存储该数据。
为了实现您的目标,您可以做两件事:每次需要验证新票证时打开您的CSV文件,并检查票号是否存在,或者 - 由于您使用的是相对少量的数据 - 将字典存储在内存中,并且只在使用结束时将其写出,检查该票证是否有效。