Python Glossary Русский

all Python 3fileinputfunction

fileinput.input()

reading a stream of files

Creates the global FileInput object that reads several files line by line in a row, or stdin when no files are given.

Syntax

fileinput.input(files=None, inplace=False, backup='', *, mode='r', openhook=None, encoding=None, errors=None)

Without a file list it takes names from sys.argv[1:], and reads stdin when that is empty; '-' in the list also means stdin. Lines keep their trailing '\n'. While a previous input() is unclosed and has started reading, a new call fails with RuntimeError 'input() already active' — so use with or fileinput.close(). Without encoding files are read in the locale encoding.

Examples

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.input(['a.txt', 'b.txt'], encoding='utf-8') as f:
    print([line.rstrip() for line in f])  # → ['a1', 'a2', 'b1', 'b2']
import fileinput
open('a.txt', 'w', encoding='utf-8').write('a1\na2\n')
for line in fileinput.input(['a.txt'], encoding='utf-8'):
    break
try:
    fileinput.input(['a.txt'], encoding='utf-8')
except RuntimeError as e:
    print(e)  # → input() already active
fileinput.close()

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy