6.5.2 读取特定行
linecache模块读取的文件行号从1开始,不过通常列表的数组索引会从0开始。
import linecache
from linecache_data import *
filename = make_tempfile()
# Pick out the same line from source and cache.
# (Notice that linecache counts from 1.)
print('SOURCE:')
print('{!r}'.format(lorem.split('\n')[4]))
print()
print('CACHE:')
print('{!r}'.format(linecache.getline(filename,5)))
cleanup(filename)
返回的各行包括末尾的一个换行符。
运行结果: