all Python 3linecachefunction
linecache.getline()
reading lines
Returns a source-file line by number (from 1) including its '\n', caching the whole file; traceback is built on it.
Syntax
linecache.getline(filename, lineno, module_globals=None)
The function never raises: a missing file or line gives an empty string '', so errors are easy to miss. Numbering starts at 1, not 0. The file is read once and cached, so after the file changes getline keeps returning the old text until checkcache is called. For modules inside a zip archive a line is available only if you pass module_globals.
Examples
import linecache
with open('data.py', 'w') as f:
f.write('x = 1\ny = 2\n')
print(repr(linecache.getline('data.py', 2))) # → 'y = 2\n'
print(repr(linecache.getline('data.py', 99))) # → ''
print(repr(linecache.getline('missing.py', 1))) # → ''
See also
Open in the full glossarydocs.python.orgReport an inaccuracy