Python快速读取文件中指定的一行或多行

使用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')

你可能感兴趣的:(python,python)