Replace Certain Lines in a Script Using Fileinput

Python
How to replace certain lines and overwrite a text file using Python’s fileinput module.
Author

Ziyue Li

Published

December 6, 2022

If we are using a script written by someone else, and we want to modify certain lines of it before execution, we can use Python’s fileinput module:

import sys
import fileinput

with fileinput.input('test.py', 
                     backup='.bak', # the file is moved to a backup file  
                     inplace=True   # and standard output is directed to the input file
                     ) as f:
    for line in f:
        if line.strip().startswith('print'):
            line = f'print("This is a new message")'            
        # lines that are written to stdout will be written to the file
        sys.stdout.write(line)

When inplace=True, as in the above code, whatever’s written to stdout, will be written to the file. You can also specify a backup file, as we did in the example.