bob*_*029 2 python csv export-to-csv
我正在努力为非营利性募捐活动创建一个简短的简单程序,以便在客人办理登机手续时验证机票号码,以确保不会兑换重复的机票.我在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))
Run Code Online (Sandbox Code Playgroud)
嗯,我想你可能有点过于复杂了!对于这样的事情,真的没有必要去解决所有麻烦.这是使用字典的好地方,对于只有两个输入的内容,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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
828 次 |
| 最近记录: |