On this page
  1. fileinput.filelineno
  2. Import
  3. Signature & Overview
  4. Usage
  5. Gotchas
  6. REPL Inspect

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

REPL Inspect

from fileinput import filelineno
help(filelineno)

Linked from

Related notes