0

I've been trying to do this, but I'm pretty new at Python, and can't figure out how to make it work.

I have this:

import fileinput
for line in fileinput.input(['tooltips.txt'], inplace=True, backup="bak.txt"):
    line.replace("oldString1", "newString1")
    line.replace("oldString2", "newString2")

But it just deletes everything from the txt.

What am I doing wrong?

I have tried with print(line.replace("oldString1", "newString1") but it doesn't remove the existing words.

As I said, I'm pretty new at this. Thanks!

4

2 回答 2

0

一种简单的方法是使用open函数和os模块:

import os
with open(tmp_file) as tmp:
    with open(my_file) as f:
        for line in f.readlines():
            tmp.write(line.replace("oldString1", "newString1").replace("oldString2", "newString2") + "\n")
os.remove(my_file)
os.rename(tmp_file, my_file)
于 2013-07-30T23:50:54.573 回答
0

line.replace()不修改line返回修改后的字符串

import fileinput, sys

for line in fileinput.input(['tooltips.txt'], inplace=True, backup="bak.txt"):
    sys.stdout.write(line.replace("oldString1", "newString1"))
于 2013-07-30T23:50:55.810 回答