2010-11-09 53 views
2

我有一個results.txt文件看起來像這樣:
的Python:替換功能來編輯文件

[["12 - 22 - 30 - 31 - 34 - 39 - 36"], 
["13 - 21 - 28 - 37 - 39 - 45 - 6"], 
["2 - 22 - 32 - 33 - 37 - 45 - 11"], 
["3 - 5 - 11 - 16 - 41 - 48 - 32"], 
["2 - 3 - 14 - 29 - 35 - 42 12"], 
["14 - 30 - 31 - 36 - 44 - 47 26"]] 

我想更換「 - 」與RESULTS.TXT文件「‘’」所以它看起來像一個Python列表。

我嘗試使用下面的代碼,但輸出長相酷似RESULTS.TXT

output = open("results2.txt", 'w') 
f = open("results.txt", 'r') 
read = f.readlines() 

for i in read: 
    i.replace(" - ",'","') 
    output.write(i) 

回答

6
for i in read: 
    # the string.replace() function don't do the change at place 
    # it's return a new string with the new changes. 
    a = i.replace(" - ",",") 
    output.write(a) 
5

String方法返回一個新的字符串。寫出來,而不是。

output.write(i.replace(" - ",",")) 
4

i.replace(" - ",'","')沒有改變i(記住string是不可改變的),所以你應該使用

i = i.replace(" - ",'","') 

如果文件不是很大(我猜 - 因爲你正在閱讀它無論如何都與readlines()一起進入內存),您可以立即執行整個文件

output = open("results2.txt", 'w') 
f = open("results.txt", 'r') 
output.write(f.read().replace(" - ".'","')) 
f.close() 
output.close()