import sys
import fileinput
for i, line in enumerate(fileinput.input('lorem_ipsum.txt', inplace=1)):
    sys.stdout.write(line.replace('sit', 'SIT'))
if i == 4:
    sys.stdout.write('\n')
How do I modify a text file in Python?