Skip to content

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:

Language: Python Filename: 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:

Language: Shell
$ 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 to sys.stdin when no files are given
  • Tracks the current filename, cumulative line number, and per-file line number
  • Supports in-place file editing by redirecting sys.stdout back to the current file
  • Optionally creates backup copies of edited files
  • Opens compressed .gz and .bz2 files transparently via the hook_compressed hook

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:

Language: Python Filename: 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:

Language: Python Filename: 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.stdin without 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:

Language: Python Filename: 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:

Language: Shell
$ 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.

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.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated April 9, 2026