我正在尝试替换文件中的多个字符串。
我的文件可能包含以下内容:
#groovy
some test
some more test
REPLACE_1
REPLACE_OPTIONAL_1
REPLACE_2
end test
我正在尝试使用fileinput模块替换上面的文本,但是它无法正常工作。我的方法是这样的:
import fileinput
def replace_method():
file_path = './file1.txt'
try:
with fileinput.FileInput(file_path, inplace=True, backup=".bak") as file:
for line in file:
print (line.replace('REPLACE_1', 'replaced_value1'), end='')
print (line.replace('REPLACE_OPTIONAL_1', 'replaced_value2'), end='')
print (line.replace('REPLACE_OPTIONAL_2', 'replaced_value3'), end='')
print (line.replace('REPLACE_2', 'replaced_value4'), end='')
except Exception as e:
print (str(e))
以上代码可以使用,但是在新的修改文件中每行打印4次。我相信这与不正确使用line.replace有关。
能帮我解决这个问题吗? 如果需要更多信息,请告诉我。
答案 0 :(得分:2)
不打印4次
import fileinput
def replace_method():
file_path = './file1.txt'
try:
with fileinput.FileInput(file_path, inplace=True, backup=".bak") as file:
for line in file:
line = line.replace('REPLACE_1', 'replaced_value1')
line = line.replace('REPLACE_OPTIONAL_1', 'replaced_value2')
line = line.replace('REPLACE_OPTIONAL_2', 'replaced_value3')
line = line.replace('REPLACE_2', 'replaced_value4')
print (line, end='')
except Exception as e:
print (str(e))
答案 1 :(得分:1)
问题是您要打印该行四次而不是一次。该修复程序可能如下所示:
import fileinput
def replace_method():
file_path = './file1.txt'
try:
with fileinput.FileInput(file_path, inplace=True, backup=".bak") as file:
for line in file:
line.replace('REPLACE_1', 'replaced_value1')
line.replace('REPLACE_OPTIONAL_1', 'replaced_value2')
line.replace('REPLACE_OPTIONAL_2', 'replaced_value3')
line.replace('REPLACE_2', 'replaced_value4')
print(line, end='')
except Exception as e:
print (str(e))