使用linecache
用缓存快速读取,使用栗子如下:
import linecache
def get_contexts(file_path, line_number):
try:
return linecache.getline(file_path, line_number)
finally:
linecache.clearcache()
if __name__ == '__main__':
print(get_contexts('test.txt', 1))
import linecache
def get_all_contexts(file_path) -> list:
try:
lines = linecache.getlines(file_path)
lines = [i.strip() for i in lines]
return lines
finally:
linecache.clearcache()
if __name__ == '__main__':
get_all_contexts('test.txt')