Python tip 6: inplace file editing
The built-in fileinput module has nice features for file processing, especially handy for multiple files and inplace editing. Here's an example:
# inplace.py
import fileinput
with fileinput.input(inplace=True) as f:
for line in f:
# do some processing
op = line.replace('search', 'replace')
# print() the text you want to write back to the input files
print(op, end='')
By default, files passed as CLI arguments will be processed:
$ python3 inplace.py *.md
If you already know which inputs have to be processed, use the files
argument. Use the backup
argument if you want to make copies of original files in case something goes wrong. See my blog post In-place file editing with fileinput module for more details and examples.
Video demo:
See my 100 Page Python Intro ebook for a short, introductory guide for the Python programming language.