使用 Python 根据搜索替换文本文件中的整行

Replace entire line in a text file based on search using Python

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

  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()