fileinput
The Python fileinput module provides helpers for iterating over lines from multiple input files or standard input in sequence. It’s commonly used to write filter-style scripts that accept file arguments or piped input without extra file-management code:
greet.py
import fileinput
with fileinput.input(encoding="utf-8") as f:
for line in f:
print(f"Line {fileinput.lineno()}: {line}", end="")
Run it from the command line:
$ echo -e "hello\nworld" | python greet.py
Line 1: hello
Line 2: world
Key Features
- Iterates over lines from one or more files listed in
sys.argv[1:], falling back tosys.stdinwhen no files are given - Tracks the current filename, cumulative line number, and per-file line number
- Supports in-place file editing by redirecting
sys.stdoutback to the current file - Optionally creates backup copies of edited files
- Opens compressed
.gzand.bz2files transparently via thehook_compressedhook
Frequently Used Classes and Functions
| Object | Type | Description |
|---|---|---|
fileinput.input() |
Function | Creates and returns a FileInput instance that iterates over lines from the given files |
fileinput.FileInput |
Class | Iterable context manager that reads lines from multiple files in sequence |
fileinput.filename() |
Function | Returns the name of the file currently being read |
fileinput.lineno() |
Function | Returns the cumulative line number across all files read so far |
fileinput.filelineno() |
Function | Returns the line number within the current file |
fileinput.isfirstline() |
Function | Returns True if the last line read was the first line of its file |
fileinput.nextfile() |
Function | Skips the remaining lines of the current file and advances to the next one |
fileinput.hook_compressed() |
Function | Returns an open hook that transparently decompresses .gz and .bz2 files |
Examples
Iterating over two files and printing each line with its per-file and cumulative line number:
count_lines.py
import fileinput
with fileinput.input(files=("a.txt", "b.txt"), encoding="utf-8") as f:
for line in f:
fname = fileinput.filename()
fline = fileinput.filelineno()
total = fileinput.lineno()
print(f"{fname}:{fline} ({total} total) {line}", end="")
Reading from compressed files transparently:
read_compressed.py
import fileinput
with fileinput.input(
files=("data.gz",),
openhook=fileinput.hook_compressed,
encoding="utf-8",
) as f:
for line in f:
print(line, end="")
Common Use Cases
The most common tasks for fileinput include:
- Writing filter scripts that read from files or piped
sys.stdinwithout code changes - Performing in-place search-and-replace across one or more text files
- Processing batches of log or data files with per-file line tracking
- Reading compressed text files without pre-decompressing them
Real-World Example
A script that removes blank lines from every file passed on the command line and saves the result back in-place, keeping a .bak backup of the originals:
strip_blank_lines.py
import fileinput
import sys
with fileinput.input(inplace=True, backup=".bak", encoding="utf-8") as f:
for line in f:
if line.strip():
sys.stdout.write(line)
Run it on the command line:
$ python strip_blank_lines.py report.txt notes.txt
Each file is rewritten without blank lines. The originals are preserved as report.txt.bak and notes.txt.bak.
Related Resources
Tutorial
Reading and Writing Files in Python (Guide)
In this tutorial, you'll learn about reading and writing files in Python. You'll cover everything from what a file is made up of to which libraries can help you along that way. You'll also take a look at some basic scenarios of file usage as well as some advanced techniques.
For additional information on related topics, take a look at the following resources:
- Python Command-Line Arguments (Tutorial)
- Build Command-Line Interfaces With Python's argparse (Tutorial)
- Python's pathlib Module: Taming the File System (Tutorial)
- Reading and Writing CSV Files in Python (Tutorial)
- Reading and Writing Files in Python (Course)
- Reading and Writing Files in Python (Quiz)
- Command Line Interfaces in Python (Course)
- Building Command Line Interfaces With argparse (Course)
- Build Command-Line Interfaces With Python's argparse (Quiz)
- Using Python's pathlib Module (Course)
- Python's pathlib Module: Taming the File System (Quiz)
- Reading and Writing CSV Files (Course)
- Reading and Writing CSV Files in Python (Quiz)
By Leodanis Pozo Ramos • Updated April 9, 2026