此错误消息有什么问题?我用Google搜索,我仍然不知道
错误消息 Traceback(最近一次调用最后一次):文件 " C:\ Users \ Acer \ Desktop \ Python Code Testing Bed \ Function 6 - 仍在 progress.py",第33行,in writer.writerow([id_,name,combinedaddress,dateprinter,timeprinter,',' .join(ingredients),totalprinter.group(1)]) ValueError:关闭文件的I / O操作
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 :(得分: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
块内。