2016-09-28 3 views
-2

이 오류 메시지의 문제점은 무엇입니까? 나는 그것을 위해 인터넷 검색하고 파일 열기 곳입니다 난 여전히 아무 생각ValueError : 닫힌 파일에 대한 입출력 작업 - 이미 Google 검색

ERROR MESSAGE Traceback (most recent call last): File "C:\Users\Acer\Desktop\Python Code Testing Bed\Function 6 - still in progress.py", line 33, in writer.writerow([id_, name, combinedaddress, dateprinter, timeprinter, ', '.join(ingredients), totalprinter.group(1)]) ValueError: I/O operation on closed file

import csv 
from itertools import groupby 
from operator import itemgetter 
import re 

with open("rofl.csv", "rb") as f, open("out.csv", "wb") as out: 
    reader = csv.reader(f) 
    next(reader) 
    writer = csv.writer(out) 
    writer.writerow(["Receipt ID","Name","Address","Date","Time","Items","Amount","Cost","Total"]) 
    groups = groupby(csv.reader(f), key=itemgetter(0)) 
    for k, v in groups: 
     v = list(v) 
     id_, name = v[0] 
     add_date_1, add_date_2 = [x[1] for x in v[1:3]] 
     combinedaddress = add_date_1+ " " +add_date_2 
     dateplustime = [ x[1] for x in v[4:8] ] 
     abcd = str(dateplustime) 
     dateprinter = re.search('(\d\d/\d\d/\d\d\d\d)\s(\d\d:\d\d)', abcd).group(1) 
     timeprinter = re.search('(\d\d/\d\d/\d\d\d\d)\s(\d\d:\d\d)', abcd).group(2) 
     transaction = [ x[1] for x in v[8:] ] 
     textwordfortransaction = str(transaction) 

     INGREDIENT_RE = re.compile(r"^\d+\s+([A-Za-z ]+)\s") 
     ingredients = [] 
     for string in textwordfortransaction: 
      match = INGREDIENT_RE.match(string) 
      if match: 
       ingredients.append(match.groups()) 
       continue 

totalprinter = re.search(r"\bTOTAL\b\s*(\d*).",textwordfortransaction) 
writer.writerow([id_, name, combinedaddress, dateprinter, timeprinter, ', '.join(ingredients), totalprinter.group(1)]) 
+0

마지막 2 줄 앞에 공백을 4 개 추가하십시오. 여기에'with' 문에 대한 좋은 글이 있습니다 http://effbot.org/zone/python-with-statement.htm –

답변

0

이 없습니다 :

with open("rofl.csv", "rb") as f, open("out.csv", "wb") as out: 

with 블록은 컨텍스트를 설정합니다. 이 컨텍스트가 남아 있으면 바로 파일이 닫힙니다. 이것은 :

writer.writerow([id_, name, combinedaddress, dateprinter, timeprinter, ', '.join(ingredients), totalprinter.group(1)]) 

...는 with 블록 밖에 있습니다. with 블록이 종료 되었기 때문에 프로그램이이 명령문에 도달 할 때까지 파일이 닫혔습니다.

write.writerow을 들여 쓰기하여 with 블록 내에 있어야합니다.

관련 문제