Replace entire line in a text file based on search

2019-03-06 20:29发布

问题:

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. I'm unable to replace that line using following code
  2. If that string starts in between then this code may not work as I'm checking line.startswith().

Please help.

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!!!!")

回答1:

You can use regular expression.

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