Python查找模式并替换整行 [英] Python find pattern and replace entire line

查看:49
本文介绍了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)

我有这个功能来替换文件中的字符串.但我想不出一个好方法来替换找到模式的整行.

I have this function to replace string in a file. But I can't figure out a good way to replace the entire line where the pattern is found.

例如,如果我想使用模式John"替换包含以下内容的行:John work hard all day",替换为Mike did not work so hard".

For example if I wanted to replace a line containining: "John worked hard all day" using pattern "John" and the replacement would be "Mike didn't work so hard".

使用我当前的函数,我必须以模式编写整行以替换整行.

With my current function I would have to write the entire line in pattern to replace the entire line.

推荐答案

首先,您可以更改此部分:

Firstly, you could change this part:

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)

或者你可以让它更漂亮:

Or you could make it even prettier:

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

这篇关于Python查找模式并替换整行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆