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.

PythonCli Tooling

Code

pythonsnippet
26 lines
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

FAQ

What does this need from the package registry?
These are real dependencies: `fileinput`. Without it the snippet will not load.