linecache.getline() in Python

Python tip:

You can get any line from a file by using the getline method from linecache:

linecache.getline(filename, lineno, module_globals=None)

It never raises an exception. Instead, it returns '' (no line with a number, no file, ...).

The trackback module uses it to retrieve source lines for formatted tracebacks.

An example👇

import linecache

Content of example. txt:


print(linecache.getline("example.txt", 2))
# => Tweet