基于使用 Python 的搜索替换文本文件中的整行 [英] Replace entire line in a text file based on search using Python

查看:67
本文介绍了基于使用 Python 的搜索替换文本文件中的整行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试替换文本文件中的 path='/users/username/folder' 形式的字符串.我正在阅读该文本文件并搜索以path ="开头的行.这里我有两个问题,

I'm trying to replace a string which will be in the form of path='/users/username/folder' in a text file. I'm reading that text file and searching the line which starts from 'path ='. Here I've two problems,

  1. 我无法使用以下代码替换该行
  2. 如果该字符串介于两者之间,则此代码可能无法正常工作,因为我正在检查 line.startswith().

请帮忙.

f = open('/Volumes/Personal/example.text','r+')

for line in f:
    print(line, end='')
    if (line.startswith("path = ")):
        # You need to include a newline if you're replacing the whole line
        line = CurrentFilePath + "\n" 
        f.write(line)
        print ("Success!!!!")

推荐答案

可以使用正则表达式.

import re
with open("filename","r+") as f:
    text = f.read()
    modified_text, modified = re.subn(r'(?:^|(?<=\n))path\s\=.*',CurrentFilePath, text)
    if  modified:
        print ("Success!!!!")
    else:
        print ("Failure :(")
    f.seek(0)  
    f.write(modified_text)  
    f.truncate()

这篇关于基于使用 Python 的搜索替换文本文件中的整行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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