# How to replace a word in a text 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.