我有一个文件,我需要在其中搜索
STR1
并替换含有
STR2
的整行。例如,
file1
包含以下数据
Name: John
Height: 6.0
Weight: 190
Eyes: Blue
我需要在上述文件中搜索Name,然后将整行替换为Name: Robert。我可以在sed中轻松地完成这个任务,如
sed -i 's/.*Name.*/Name:Robert/' file1
但如何在Python中得到同样的结果。例如,我可以用fileinput将一个字符串替换成另一个字符串,如下所示
#! /usr/bin/python
import fileinput
for line in fileinput.input("file1", inplace=True):
# inside this loop the STDOUT will be redirected to the file
# the comma after each print statement is needed to avoid double line breaks
print line.replace("Name: John", "Name: Robert"),
如何修改上述代码以替换整行,使用'*'替换文件中的所有行,即使有一个搜索条件(if "Name" in line)。