linecache2

1.0.0 · maintenance · verified Sat Apr 11

linecache2 is a Python library providing backports of the standard library's `linecache` module to older supported Python versions (specifically Python 2.6, 3.2, 3.3, and 3.4). It enables random access to individual lines from text files, optimizing internally through a cache, similar to the built-in module. The current version is 1.0.0, released in March 2015, and its development status is 'Mature', indicating stability rather than active feature development.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `linecache2` to retrieve specific lines from a file, similar to the standard `linecache` module. It includes examples of `getline` to fetch a line by its number, `checkcache` to update cache entries, and `clearcache` to remove cached data. The core functionality mirrors the standard library, but with compatibility for older Python versions.

import os
from linecache2 import getline, clearcache, checkcache

# Create a dummy file for demonstration
filename = 'example_file.py'
with open(filename, 'w') as f:
    f.write('print("Hello, world!")\n')
    f.write('x = 10\n')
    f.write('y = x + 5\n')
    f.write('print(f"The value of y is {y}")\n')

# Get a specific line from the file
line_2 = getline(filename, 2)
print(f"Line 2: {line_2.strip()}")

# Check if the cache needs updating (e.g., if the file changed on disk)
checkcache(filename)

# Clear the cache for a specific file or entirely
clearcache(filename)

# Verify line is empty after clearing cache (unless re-read)
# line_2_after_clear = getline(filename, 2) # This would re-read and cache it again

# Clean up the dummy file
os.remove(filename)

view raw JSON →