fileinput Streams CLI Line Context
fileinput reads CLI file arguments in sequence, tracks global and per-file line numbers, and rewrites files in place with a backup extension.
Code
import fileinput
from pathlib import Path
for name in ('access.log', 'error.log'):
Path(name).write_text('2026-11-21 boot\n2026-11-21 auth ok\n', encoding='utf-8')
# 多文件顺序读取:lineno() 跨文件连续,filename() 报告当前来源
with fileinput.input(files=('access.log', 'error.log')) as lines:
for line in lines:
print(f'{fileinput.filename()}:{fileinput.lineno()}: {line}', end='')
print()
# filelineno() 只统计当前文件内的行号,换文件时归零
with fileinput.input(files=('access.log', 'error.log')) as lines:
for line in lines:
print(f'{fileinput.filename()}#{fileinput.filelineno()}', end=' ')
print()
# inplace 模式:循环里的 print 写回原文件,backup 先留 .bak
with fileinput.input(files='access.log', inplace=True, backup='.bak') as lines:
for line in lines:
print(line.strip().upper())
print(Path('access.log').read_text(encoding='utf-8'))fileinput Streams CLI Line Context: the mechanics
Repetition is confined to for name in ('access.log', 'error.log') — the rest of the file is straight-line. From fileinput it pulls Path — the imports name exactly which library surface the snippet touches.
Points of care
- External dependency:
fileinput— install it before running the snippet.
Statements that matter
with fileinput.input(files='access.log', inplace=True, backup='.bak') as lines:
for line in lines:
print(line.strip().upper())
with fileinput.input(files=('access.log', 'error.log')) as lines:
for line in lines:
print(f'{fileinput.filename()}:{fileinput.lineno()}: {line}', end='')
with fileinput.input(files=('access.log', 'error.log')) as lines:
for line in lines:
print(f'{fileinput.filename()}#{fileinput.filelineno()}', end=' ')
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- What does this need from the package registry?
- These are real dependencies: `fileinput`. Without it the snippet will not load.
Report a problem with this exampleOpens a pre-filled issue on GitHub.