Python:替换函数以编辑文件
我有一个叫做 results.txt
的文件,里面的内容是这样的:
[["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"]]
我想把这个文件里的 " - " 替换成 '","',这样看起来就像一个 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)
3 个回答
4
i.replace(" - ",'","')
这个操作不会改变 i
的内容(记住,字符串是不可变的),所以你应该使用
i = i.replace(" - ",'","')
如果文件不太大(我猜是这样,因为你用 readlines()
一次性把它全部读入内存),你可以一次性处理整个文件
output = open("results2.txt", 'w')
f = open("results.txt", 'r')
output.write(f.read().replace(" - ".'","'))
f.close()
output.close()
5
字符串的方法会返回一个新的字符串。直接写出这个新的字符串就可以了。
output.write(i.replace(" - ",","))
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)
当然可以!请把你想要翻译的内容发给我,我会帮你把它变得简单易懂。