Question from the side of application programming of working scripts under * nix systems.
Until recently, I used the standard construction of reading files:
with open (file_path, 'r') as f: with_open_open = f.read () # f.readline (), f.readlines (), ...
Found in the comments of the Russian SO community a mention of the
fileinput module for 3 years I have never read about it anywhere.
Question: which use cases of this module are warranted and when should you avoid using it?
Answer 1, authority 100%
From module description :
This module implements a helper class and functions to quickly write a
loop over standard input or a list of files. If you just want to read
or write one file see
Ie all the advantages of this module open up when you need to process streaming standard input (STDIN) or several files at once. To work with a single file, developers are advised to refer to
open () …
This module also allows you to implement filtering / processing of files “in place” (
inplace = True ), creating a backup copy of the file (
backup = .extension )
#! / usr / bin / env python import sys, re, fileinput pattern = re.compile (sys.argv ) for line in fileinput.input (sys.argv [2:]): if pattern.match (line): print (fileinput.filename (), fileinput.filelineno (), line)