加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python查找模式并替换整行

发布时间:2020-12-20 11:30: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
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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读