2017-04-08 3 views
2

중복 티켓을 사용할 수 없도록 손님이 체크인 할 때 티켓 번호의 유효성을 검사하기위한 간단한 비영리 기금 모금 활동 프로그램을 만들고 있습니다. Windows 10 시스템에서 Python 3.4.3을 실행하고 있습니다. 프로그램이 완료되면 기금 모금 행사에서 터치 스크린이있는 라즈베리 파이 (Raspberry Pi)에 사용됩니다.TypeError : 'DictWriter'객체가 반복 가능하지 않습니다.

나는리스트를 만들고, 저장하고, 중복을 검색하기 위해 몇 가지 다른 방법을 시도했다. 이상적으로 목록은 CSV 파일에 저장되지만 일반 텍스트 또는 다른 형식도 괜찮습니다.

중복 티켓을 사용할 수 없도록 파일에 저장된 티켓과 티켓 #을 비교하는 루핑 기능으로 인해 추적 오류 (TypeError : 'DictWriter'개체를 반복 할 수 없음)를 사용할 수 있습니까?

도움을 주셔서 감사합니다. csv.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)) 

답변

5

흠, 조금 복잡해 보였습니다. 그런 식으로 모든 문제를 해결할 필요가 없습니다. 이것은 사전을 사용하는 가장 좋은 장소이며, 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() 
0

객체는, 반복 가능하지 않은 즉 당신이 당신처럼 그들을 것 사전, 목록, 또는 문자열, 따라서 귀하의 오류 메시지를 반복 할 수. 이전에 파일에 작성한 데이터는 저장하지 않고 작성한 파일 만 해당 데이터를 저장합니다.

목표를 달성하려면 새로운 티켓의 유효성을 검사해야 할 때마다 CSV 파일을 열고 티켓 번호가 있는지 확인하거나 비교적 소량 - 사전을 메모리에 저장하고 사용 종료시에만 사전에 기록하고 티켓이 유효한지 확인하십시오.

관련 문제