On this page
  1. fileinput
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. In-Place File Editing with Backup
  7. 2. Reading Compressed Inputs Transparently
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects

fileinput

Prev: filecmp | Up: stdlib_module | Next: fnmatch
Rel: pathlib, os, io, time, stat
Ref: docs.python.org — fileinput
Tags: #public #python3 #stdlib


Import

import fileinput

Overview

Utility for iterating line-by-line across multiple input files (or sys.stdin when no files are given), mimicking classic Unix filters like sed and awk. Reach for fileinput when writing quick CLI text-processing filters or in-place file rewriters with automatic .bak backups.

Quick Start

import fileinput
from pathlib import Path
import tempfile

with tempfile.TemporaryDirectory() as tmp:
    p1 = Path(tmp) / "a.txt"
    p2 = Path(tmp) / "b.txt"
    p1.write_text("alpha\nbeta\n", encoding="utf-8")
    p2.write_text("gamma\n", encoding="utf-8")

    with fileinput.input(files=(p1, p2), encoding="utf-8") as f:
        lines = [(Path(f.filename()).name, f.filelineno(), line.strip()) for line in f]

assert lines == [("a.txt", 1, "alpha"), ("a.txt", 2, "beta"), ("b.txt", 1, "gamma")]

Implementation Walkthrough

1. In-Place File Editing with Backup

Setting inplace=True redirects sys.stdout to each file being read, so print() writes directly back to the file while preserving an optional backup:

import fileinput
from pathlib import Path
import tempfile

with tempfile.TemporaryDirectory() as tmp:
    cfg = Path(tmp) / "app.cfg"
    cfg.write_text("mode=debug\nport=8000\n", encoding="utf-8")

    with fileinput.input(files=(cfg,), inplace=True, backup=".bak", encoding="utf-8") as f:
        for line in f:
            print(line.replace("debug", "prod"), end="")

    assert "mode=prod" in cfg.read_text(encoding="utf-8")
    assert (Path(tmp) / "app.cfg.bak").exists()

2. Reading Compressed Inputs Transparently

Pass openhook=fileinput.hook_compressed to automatically decompress .gz and .bz2 files alongside plain text files.

Gotchas & Boundaries

Common Functions

Classes & Objects

Linked from

Related notes