2014-03-03 49 views
0

這是我的代碼的一部分,我嘗試運行它,並在第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) 
+9

您在'for'循環中關閉文件。由於第一次迭代是開放式的,但從那時起它就被關閉了。 – Ffisegydd

+0

代碼的用途是什麼?在for循環中可能有比使用兩個文件句柄更清晰的算法來完成你想要完成的任務 – crennie

+0

任何依賴操縱Python對象的字符串值的代碼都應該被認爲是高度可疑的。 – holdenweb

回答

1

Jambofun已經解釋了原因。這裏是做的更有效的方法:

c.execute("SELECT * FROM Student, Behaviour") 
data = c.fetchall() 
currentRecords = open('Current Records - Unsorted', 'w') 
dashes = '----------------------------------' 
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(","," -") 
    record = "\r\n".join((record, dashes)) + "\r\n" 
    currentRecords.write(record) 

    l.append(''.join(l)) 

注意最後一行,我不知道你在做你想做的事。你正在積累所有的記錄。

1

您似乎想寫出用破折號分隔的字段值。讓我們看看正確的方式來做到這一點。

你需要的代碼是:

record = "\r\n{}\r\n".format("-".join(str(f) for f in row)) 

這每個字段轉換爲字符串(如果它是不是已經一個),並加入了破折號的字符串,然後插入該行尾之間。

相關問題