python读取文件固定行

内置库 linecache

1
2
3
4
5
6
7
8
9

>>> import linecache
>>> file_path = r'D:\work\python\test.txt'
>>> line_number = 5
>>> def get_line_context(file_path, line_number):
... return linecache.getline(file_path, line_number).strip()
...
>>> get_line_context(file_path, line_number)
'This is line 5.'