how to fully replace text in textfile using python code example
Example: python replace text in file
filename = "sample1.txt"
# SAMPLE1.TXT
# Hello World!
# I am a human.
with open(filename, 'r+') as f:
text = f.read()
text = re.sub('human', 'cat', text)
f.seek(0)
f.write(text)
f.truncate()
# SAMPLE1.TXT
# Hello World!
# I am a cat.