2011-06-13 241 views
0

我有一個XML文件,其中包含非法字符,我遍歷文件,從所有行中刪除字符並將行存儲在列表中。我現在想把這些相同的行寫回文件並覆蓋已經存在的內容。讀取和寫入文件

我嘗試這樣做:

file = open(filename, "r+") 
#do stuff 

這是隻將結果追加到文件的末尾,我想覆蓋現有文件。

這:

file = open(filename, "r") 
#read from the file 
file.close() 

file = open(filename, "w") 
#write to file 
file.close() 

這給了我一個錯誤的文件描述符錯誤。

我該如何讀寫同一個文件?

謝謝

+3

的第二代碼片段是正確的方式。你能顯示錯誤信息(完整追溯)嗎?什麼操作系統/文件系統? – 2011-06-13 20:01:51

+5

無論如何,你真的想用'open(文件名,模式)'作爲文件:'每次你處理文件。否則,你需要相當多的醜陋和可避免的樣板代碼才能確保文件正確關閉。 – delnan 2011-06-13 20:03:13

+0

你能舉一個例子嗎? – 2011-06-13 20:10:34

回答

0

你一直追加到文件末尾的原因是你需要尋找文件的開頭來寫出你的行。

with open(filename, "r+") as file: 
    lines = file.readlines() 

    lines = [line.replace(bad_character, '') for line in lines] 

    file.seek(0) 
    file.writelines(lines) 
    file.truncate()   # Will get rid of any excess characters left at the end of the file due to the length of your new file being shorter than the old one, as you've removed characters. 

(決定只使用情況管理器語法自己。)

+0

謝謝,這正是什麼我在尋找。 – 2011-06-13 20:10:48

+0

不客氣。 – JAB 2011-06-13 23:30:53

2

你可以用writelines函數重寫行列表。

with open(filename, "r") as f: 

    lines = f.readlines() 

#edit lines here 

with open(filename, "w") as f: 

    f.writelines(lines)