Python Fileinput Module
The fileinput module implements a helper class and functions to quickly write a loop over standard input or a list of files. This is useful for writing filter scripts that process input streams line by line.
Importing the Module
import fileinput
Basic Usage
The typical use case is to iterate over the lines of all files listed in sys.argv[1:], defaulting to sys.stdin if the list is empty.
import fileinput
for line in fileinput.input():
print(f"Processing: {line}", end='')
You can run this script like: python script.py file1.txt file2.txt.
Specifying Files
You can explicitly pass a list of filenames to fileinput.input().
import fileinput
files = ['data1.txt', 'data2.txt']
with fileinput.input(files=files) as f:
for line in f:
print(line, end='')
In-Place Editing
The module supports in-place editing of files. When inplace=True is passed to fileinput.input(), standard output is redirected to the input file.
import fileinput
# Adds line numbers to a file, modifying it in-place
with fileinput.input(files=('test.txt',), inplace=True, backup='.bak') as f:
for line in f:
print(f"{f.lineno()} {line}", end='')
File Metadata
You can access information about the current file and line being processed.
fileinput.filename(): Name of the file currently being read.fileinput.lineno(): Cumulative line number.fileinput.filelineno(): Line number in the current file.fileinput.isfirstline(): True if the line read is the first line of its file.
import fileinput
for line in fileinput.input():
if fileinput.isfirstline():
print(f"--- Reading {fileinput.filename()} ---")
print(f"Line {fileinput.filelineno()}: {line}", end='')