Python Glossary Русский

all Python 3fileinputfunction

fileinput.filename()

reading state

Returns the name of the file the last line of fileinput.input() was read from.

Syntax

fileinput.filename() -> str | None

Before the first line is read it returns None, and for stdin the string '<stdin>'. The name comes back exactly as it was passed: a relative path stays relative. Without an active input() it raises RuntimeError rather than returning None. Inside the loop it pairs well with filelineno() for "file:line" labels.

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(fileinput.filename())  # → None
    for line in f:
        print(f'{fileinput.filename()}:{fileinput.filelineno()}')  # → a.txt:1 / a.txt:2 / b.txt:1 / b.txt:2

See also

Open in the full glossarydocs.python.orgReport an inaccuracy