Replace Entire Line In A Text File Based On Search Using Python
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
Solution 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()
Post a Comment for "Replace Entire Line In A Text File Based On Search Using Python"