Replace entire line in a text file based on search

2019-03-06 21:04发布

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条回答
贼婆χ
2楼-- · 2019-03-06 21:29

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()
查看更多
登录 后发表回答