all Python 3fileinputterm
fileinput.FileInput
reading a stream of files
The class behind fileinput: an iterator over the lines of a set of files that tracks line numbers and the current file name.
Syntax
fileinput.FileInput(files=None, inplace=False, backup='', *, mode='r', openhook=None, encoding=None, errors=None)
A separate instance does not touch the module's global state, so two FileInput objects can be read at the same time — impossible with fileinput.input(). Its methods filename(), lineno(), nextfile() and the rest mirror the module functions. mode accepts only 'r' and 'rb'; indexing as f[0] was removed in 3.11. inplace=True cannot be combined with openhook.
Examples
# Python 3.11+
import fileinput
open('a.txt', 'w', encoding='utf-8').write('a1\na2\n')
open('b.txt', 'w', encoding='utf-8').write('b1\nb2\n')
with fileinput.FileInput(['a.txt'], encoding='utf-8') as fa, fileinput.FileInput(['b.txt'], encoding='utf-8') as fb:
print([x.strip() + y.strip() for x, y in zip(fa, fb)]) # → ['a1b1', 'a2b2']
try:
fileinput.FileInput(['a.txt'], mode='w')
except ValueError as e:
print(e) # → FileInput opening mode must be 'r' or 'rb'
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy