Filesystem and I/O Modules

linecache

Retrieves text lines by one-based line number, using a cache to avoid repeatedly reading source files. getline() returns an empty string when the requested line cannot be found. Use checkcache() or clearcache() if file contents change; this is not a general random-access binary reader.

Formal Syntax & Structure

python syntaxpython
import linecache

Return Value

module

Module namespace available through import; import is a statement, not a value-returning expression.

Working Example

Example Snippetpython
import linecachefrom pathlib import Pathfrom tempfile import TemporaryDirectorywith TemporaryDirectory() as folder:    path = Path(folder)/"sample.py"    path.write_text("a = 1\nb = 2\n", encoding="utf-8")    print(linecache.getline(str(path), 2).strip())    linecache.clearcache()
Python Reference