On this page
fileinput.filelineno
Prev: fileinput.FileInput | Up: fileinput | Next: fileinput.filename
Rel: fileinput.close, fileinput.FileInput, fileinput.filename, fileinput.fileno
Ref: docs.python.org — fileinput.filelineno
Tags: #public #python3 #stdlib #fileinput
Import
import fileinput
from fileinput import filelineno
Signature & Overview
fileinput.filelineno()
Return the line number in the current file. Before the first line has been read, returns 0. After the last line of the last file has been read, returns the line number of that line within the file.
Usage
import fileinput
from pathlib import Path
import tempfile
with tempfile.TemporaryDirectory() as tmp:
p = Path(tmp) / "a.txt"
p.write_text("x\ny\n", encoding="utf-8")
with fileinput.input(files=(p,), encoding="utf-8") as f:
nums = [(f.filelineno(), line.strip()) for line in f]
assert nums == [(1, "x"), (2, "y")]
Gotchas
- 1-based line number within the current file (resets to 1 on each new file, unlike
lineno()).
REPL Inspect
from fileinput import filelineno
help(filelineno)
Linked from
- tuts/python3/stdlib_module/fileinput
- tuts/python3/stdlib_module/fileinput/close
- tuts/python3/stdlib_module/fileinput/FileInput
- tuts/python3/stdlib_module/fileinput/filename
- tuts/python3/stdlib_module/fileinput/fileno
- tuts/python3/stdlib_module/fileinput/hook_compressed
- tuts/python3/stdlib_module/fileinput/hook_encoded
- tuts/python3/stdlib_module/fileinput/input
- tuts/python3/stdlib_module/fileinput/isfirstline
- tuts/python3/stdlib_module/fileinput/isstdin
- tuts/python3/stdlib_module/fileinput/lineno
- tuts/python3/stdlib_module/fileinput/nextfile
Related notes
- tuts/python3/stdlib_module/fileinput/close Linked here; links to this page; shared tags: #fileinput, #stdlib
- tuts/python3/stdlib_module/fileinput/FileInput Linked here; links to this page; shared tags: #fileinput, #stdlib
- tuts/python3/stdlib_module/fileinput/filename Linked here; links to this page; shared tags: #fileinput, #stdlib
- tuts/python3/stdlib_module/fileinput/fileno Linked here; links to this page; shared tags: #fileinput, #stdlib
- tuts/python3/stdlib_module/fileinput/hook_compressed links to this page; shared tags: #fileinput, #stdlib
- tuts/python3/stdlib_module/fileinput/hook_encoded links to this page; shared tags: #fileinput, #stdlib
- tuts/python3/stdlib_module/fileinput/input links to this page; shared tags: #fileinput, #stdlib
- tuts/python3/stdlib_module/fileinput/isfirstline links to this page; shared tags: #fileinput, #stdlib
- tuts/python3/stdlib_module/fileinput/isstdin links to this page; shared tags: #fileinput, #stdlib
- tuts/python3/stdlib_module/fileinput/lineno links to this page; shared tags: #fileinput, #stdlib