On this page
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
- Global singleton state: The module-level functions (
fileinput.filename(),fileinput.lineno()) operate on a globalFileInputinstance. Use the context manager (with fileinput.input(...) as f:) and call methods onfdirectly. inplace=Truehijackssys.stdout: Any strayprint()call while iterating writes into the target file; send diagnostics tosys.stderrinstead.- Defaults to
sys.argv[1:]: Callingfileinput.input()with nofiles=argument parses CLI arguments as filenames (and readssys.stdinif none are present), which can clash with argparse flags if you don't passfiles=args.files.
Common Functions
- fileinput.close() —
close()— Close the sequence. - fileinput.filelineno() —
filelineno()— Return the line number in the current file. Before the first line has been read, returns 0. After the last line of the last file has been read, returns the line number of that line within the file. - fileinput.filename() —
filename()— Return the name of the file currently being read. - fileinput.fileno() —
fileno()— Return the file number of the current file. When no file is currently opened, returns -1. - fileinput.hook_compressed() —
hook_compressed(filename, mode, *, encoding=None, errors=None)—fileinput.hook_compressed()function. - fileinput.hook_encoded() —
hook_encoded(encoding, errors=None)—fileinput.hook_encoded()function. - fileinput.input() —
input(files=None, inplace=False, backup='', *, mode='r', openhook=None, encoding=None, errors=None)— Return an instance of the FileInput class, which can be iterated. - fileinput.isfirstline() —
isfirstline()— Returns true the line just read is the first line of its file, otherwise returns false. - fileinput.isstdin() —
isstdin()— Returns true if the last line was read from sys.stdin, otherwise returns false. - fileinput.lineno() —
lineno()— Return the cumulative line number of the line that has just been read. - fileinput.nextfile() —
nextfile()— Close the current file so that the next iteration will read the first line from the next file (if any); lines not read from the file will not count towards the cumulative line count. The filename is not
Classes & Objects
- fileinput.FileInput — Class FileInput is the implementation of the module; its methods filename(), lineno(), fileline(), isfirstline(), isstdin(), fileno(), nextfile() and close() correspond to the functions of the same name (Methods:
.close(),.filelineno(),.filename(),.fileno(),.isfirstline(),.isstdin())
Linked from
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/filecmp
- tuts/python3/stdlib_module/fnmatch
- tuts/python3/stdlib_module/genericpath
- tuts/python3/stdlib_module/glob
- tuts/python3/stdlib_module/io
- tuts/python3/stdlib_module/linecache
- tuts/python3/stdlib_module/ntpath
- tuts/python3/stdlib_module/os
- tuts/python3/stdlib_module/pathlib
- tuts/python3/stdlib_module/posixpath
- tuts/python3/stdlib_module/shutil
- tuts/python3/stdlib_module/stat
- tuts/python3/stdlib_module/stdlib_module
- tuts/python3/stdlib_module/tempfile
- tuts/python3/stdlib_module/time
Related notes
- tuts/python3/stdlib_module/filecmp Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/fnmatch Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/io Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/os Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/pathlib Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/stat Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/time Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/argparse Linked here; shared tags: #stdlib