linecache
The Python linecache module provides random access to individual lines of a text file while keeping previously read lines in an internal cache. It was designed to support the traceback module, which repeatedly retrieves source lines when formatting error reports, but it is equally useful for any task that jumps around in a file by line number.
Here’s a quick example:
>>> import linecache
>>> linecache.getline(linecache.__file__, 1)
'"""Cache lines from Python source files.\n'
Each call returns the requested line, including its terminating newline, and keeps the file contents cached so that subsequent lookups avoid reading from disk.
Key Features
- Retrieves arbitrary lines by number without rereading the file on each call
- Caches file contents in memory for fast repeated access
- Returns an empty string instead of raising an exception when a file or line does not exist
- Uses
tokenize.open()to detect a Python source file’s declared encoding automatically - Resolves relative filenames through
sys.path, which lets it locate imported modules - Supports PEP 302 loaders and frozen modules through the optional
module_globalsargument
Frequently Used Classes and Functions
| Object | Type | Description |
|---|---|---|
linecache.getline() |
Function | Returns a specific line from a file, or an empty string on error |
linecache.clearcache() |
Function | Discards all cached lines from memory |
linecache.checkcache() |
Function | Rechecks cached entries against the files on disk and drops stale ones |
linecache.lazycache() |
Function | Registers a non-file module so its source can be fetched on demand |
Examples
Reading a specific line from a Python source file on disk:
>>> import linecache
>>> linecache.getline(linecache.__file__, 8)
'__all__ = ["getline", "clearcache", "checkcache", "lazycache"]\n'
Handling missing files and out-of-range line numbers without raising an exception:
>>> import linecache
>>> linecache.getline("does_not_exist.py", 1)
''
>>> linecache.getline(linecache.__file__, 999999)
''
Refreshing the cache after a file has been modified or removed:
>>> import linecache
>>> from pathlib import Path
>>> sample = Path("/tmp/notes.txt")
>>> _ = sample.write_text("first line\nsecond line\n")
>>> linecache.getline(str(sample), 2)
'second line\n'
>>> _ = sample.write_text("brand new content\n")
>>> linecache.checkcache(str(sample))
>>> linecache.getline(str(sample), 1)
'brand new content\n'
Releasing all cached data when a long-running program no longer needs it:
>>> import linecache
>>> linecache.clearcache()
Common Use Cases
The most common tasks for linecache include:
- Supplying source snippets inside custom traceback formatters
- Rendering contextual error messages in linters, type checkers, and compilers
- Highlighting a target line inside a code viewer, REPL helper, or debugger
- Building grep-like utilities that print a few surrounding lines for each match
- Reading scattered lines from large files without buffering the entire contents
Real-World Example
Consider a small debugging helper that prints a target line along with a few neighbors, similar to what traceback shows when an exception propagates. The linecache module makes each lookup cheap, so the helper can display several lines without reopening the file:
>>> import linecache
>>> from pathlib import Path
>>> source = Path("/tmp/sample_script.py")
>>> _ = source.write_text(
... "def greet(name):\n"
... " print(f'Hello, {name}!')\n"
... "\n"
... "def farewell(name):\n"
... " print(f'Bye, {name}!')\n"
... )
>>> def show_context(path, target, radius=1):
... for number in range(target - radius, target + radius + 1):
... line = linecache.getline(str(path), number)
... if line:
... marker = ">" if number == target else " "
... print(f"{marker} {number:>3}: {line.rstrip()}")
...
>>> show_context(source, 4)
3:
> 4: def farewell(name):
5: print(f'Bye, {name}!')
The helper calls getline() once per line in the surrounding window and relies on the cache so that later calls against the same file return immediately. Swapping linecache for a direct open() would force the helper to reread the file on every invocation.
Related Resources
Tutorial
Understanding the Python Traceback
In this step-by-step tutorial, you'll learn how to read and understand the information you can get from a Python traceback. You'll walk through several examples of tracebacks and see some of the most common tracebacks in Python.
For additional information on related topics, take a look at the following resources:
- How to Debug Common Python Errors (Tutorial)
- Python Exceptions: An Introduction (Tutorial)
- Reading and Writing Files in Python (Guide) (Tutorial)
- Python Debugging With Pdb (Tutorial)
- Unicode & Character Encodings in Python: A Painless Guide (Tutorial)
- Getting the Most Out of a Python Traceback (Course)
- How to Debug Common Python Errors (Quiz)
- Introduction to Python Exceptions (Course)
- Raising and Handling Python Exceptions (Course)
- Python Exceptions: An Introduction (Quiz)
- Reading and Writing Files in Python (Course)
- Reading and Writing Files in Python (Quiz)
- Debugging in Python With pdb (Course)
- Unicode in Python: Working With Character Encodings (Course)
By Leodanis Pozo Ramos • Updated April 23, 2026