【发布时间】:2014-04-05 00:03:54
【问题描述】:
这是我的代码的一部分,我尝试运行它并在此处的第 12 行收到此错误:ValueError: I/O operation on closed file。但我确信文件“currentRecords”是打开的。怎么了?
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循环中关闭文件。因此,第一次迭代它是开放的,但从那时起它就关闭了。 -
代码的用途是什么?对于您想要完成的任务,可能有比在
for-loop中使用两个文件句柄更清晰的算法 -
任何依赖于操作 Python 对象的字符串值的代码都应该被视为高度可疑的。
-
我认为这段代码的最后六行不应该缩进。
标签: python file for-loop input output