python replace a line in text file 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.