Python查找模式并替换整行

def replace(file_path, pattern, subst):
   file_path = os.path.abspath(file_path)
   #Create temp file
   fh, abs_path = mkstemp()
   new_file = open(abs_path,'w')
   old_file = open(file_path)
   for line in old_file:
       new_file.write(line.replace(pattern, subst))
   #close temp file
   new_file.close()
   close(fh)
   old_file.close()
   #Remove original file
   remove(file_path)
   #Move new file
   move(abs_path, file_path)

我有这个函数来替换文件中的字符串.但我无法找到替换找到模式的整条线的好方法.

例如,如果我想替换一行包含:“John整天努力工作”使用模式“John”,替换将是“Mike没有那么努力”.

使用我当前的函数,我将不得不在模式中写入整行以替换整行.

最佳答案 首先,您可以更改此部分:

for line in old_file:
    new_file.write(line.replace(pattern, subst))

进入:

for line in old_file:
    if pattern in line:
        new_file.write(subst)
    else:
        new_file.write(line)

或者你可以让它更漂亮:

for line in old_file:
    new_file.write(subst if pattern in line else line)
点赞