2010-11-09 54 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()