我正在尝试替换文件中的多个字符串。
我的文件可能包含如下内容:
文件1:
#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 有关。
你能帮我解决这个问题吗? 如果您需要更多信息,请告诉我。
最佳答案
不要打印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))
关于python - 使用 fileinput 替换文件中的多个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56001870/