Python Glossary Русский

all Python 3fileinputfunction

fileinput.close()

reading a stream of files

Closes the current fileinput.input() sequence and releases the module's global state.

Syntax

fileinput.close()

If the loop is left with break the file stays open and the next input() fails with RuntimeError — close() (or with) fixes that. After close() the state functions such as filename() and lineno() raise RuntimeError 'no active input()'. With inplace=True it is the close that restores stdout and removes the temporary backup.

Examples

import fileinput
open('a.txt', 'w', encoding='utf-8').write('a1\na2\n')
for line in fileinput.input(['a.txt'], encoding='utf-8'):
    break
fileinput.close()
try:
    fileinput.lineno()
except RuntimeError as e:
    print(e)  # → no active input()

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy