Home python What is the advantage of the Python module - fileinput?

What is the advantage of the Python module – fileinput?

Author

Date

Category

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 open () .

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 )


Example usage – implementation of the grep utility in Python :

#! / usr / bin / env python
import sys, re, fileinput
pattern = re.compile (sys.argv [1])
for line in fileinput.input (sys.argv [2:]):
  if pattern.match (line):
    print (fileinput.filename (), fileinput.filelineno (), line)

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions