值错误:对具有"with"块的缩进文件上的关闭文件执行 I/O 操作


with open('C:\Users\Download.csv', 'r') as file :
filedata = csv.reader(file, delimiter=',', quotechar='|')
for c in range(sum(1 for row in filedata)):
for d in range(80):
data_found = data_to_match.search(filedata)
if data_found != None:
data_found_new = str(data_found.group(0)).replace(',','.')
filedata = filedata.replace(str(data_found.group(0)) , data_found_new)
for e in range(80):
data_found_2 = data_to_match_2.search(filedata)
if data_found_2 != None:
data_found_2_new = str(data_found_2.group(0)).replace(', ', '; ')
filedata = filedata.replace(str(data_found_2.group(0)),data_found_2_new)
with open('C:\Users\Download.csv', 'w', newline='') as file2:
writer = csv.writer(file2, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
writer.writerows(filedata)

这给了我一个ValueError:对已关闭文件的I/O操作(对于行写入程序.writerows(filedata))。我试图查找错误,但发现的都是没有缩进代码的人。但至少在我看来,这不是问题所在。

编辑:示例输入

文件的第一行:"Datum"、"Uhrzeit"、"Zeitzone"、"Name"、"Typ"、"Status"、"Währung"、"Brutto"、"Gebühr","Netto"、"Absender电子邮件地址"、"Empfänger电子邮件地址","交易代码","Lieferadresse","地址状态","Artikelbezeichung"、"Artikelnummer"、"Versand-und Bearbeitungsgebühr","Versicherungsbetrag"、"Umsatzsteuer"、"Option 1 Name"、"Options 1 Wert","选项2名称","选项2 Wert","Zugehöriger交易代码","Rechnungsnummer"Zollsummer"Anzahl"Empfangsnummer"Guthaben","Adresszeile1"、"Adresszusatz"、"Ort"、"Bundesland"、"PLZ"、"Land"、"Telefon","Betreff"、"Hinweis"、"Ländervorwahl"、"Auswirkung auf Guthaben">

文件的第二行:"2019年3月2日","11:25:51","PST","Delivery Hero Germany GmbH-Lieferhold","PayPal Express Zahlung","Abgeschlossen","EUR","-12,35","0,00","-12,35","jjjjjjj@gmail.com","cc_finance@deliveryhero.com","00000000000","111 jjjjj Straße,aaaaaaa,55555,Deutschland","Bestätigt","1111111111111","11111111","0,00",","0,00",",","444444444444","Lieferheld_DE:111111111111111:1111111111:11111111111:贝宝","1",","-12,35","111 jjjjj Straße",","aaaaaaa",","555555","Deutschland",""99999999999999""DE"Soll">

解决方案1:

变量"filedata"在内部有打开的块,它是csv对象。所以,一旦你离开这个块,这个文件就会自动关闭,你在第二个块中使用相同的filedata对象。

最好取一个变量,把csv对象的所有值都放进去,然后用开放块传给第二个。

f2 = []
with open('C:\Users\Download.csv', 'r') as file :
filedata = csv.reader(file, delimiter=',', quotechar='|')
for x in filedata:
f2.append(x)
with open('C:\Users\Download.csv', 'w') as file2:
writer = csv.writer(file2, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
writer.writerows(f2)

解决方案2:不要在第一个区块中使用open,只使用open。

f_obj = open('C:\Users\Download.csv', 'r')
filedata = csv.reader(f_obj, delimiter=',', quotechar='|')
with open('C:\Users\Download.csv', 'w') as file2:
writer = csv.writer(file2, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
writer.writerows(filedata)

相关内容

  • 没有找到相关文章