這是我的代碼的一部分,我嘗試運行它,並在第12行接收到此錯誤:ValueError:關閉文件上的I/O操作。但我確信文件'currentRecords'是打開的。哪裏不對?爲什麼我會遇到I/O錯誤?
c.execute("SELECT * FROM Student, Behaviour")
data = c.fetchall()
currentRecords = open('Current Records - Unsorted', 'w')
l = []
for i in data: #for individual records in the whole database do:
record = str(i)
record = record.replace("u'","")
record = record.replace("'", "")
record = record.replace("(","")
record = record.replace(")", "")
record = record.replace(","," -")
currentRecords.write(record+"\r\n")
currentRecords.write('----------------------------------'+"\r\n")
currentRecords.close()
y = open('Current Records - Unsorted','r')
z = y.read() #opening the file containing the unsorted, formatted records to read
l.append(z)
y.close() #z is an array that holds all the records (each record has its own index within l)
您在'for'循環中關閉文件。由於第一次迭代是開放式的,但從那時起它就被關閉了。 – Ffisegydd
代碼的用途是什麼?在for循環中可能有比使用兩個文件句柄更清晰的算法來完成你想要完成的任務 – crennie
任何依賴操縱Python對象的字符串值的代碼都應該被認爲是高度可疑的。 – holdenweb