python快速讀取大文件的最后n行


方法1 使用file.seek,從文件尾部指定字節讀取(推薦):

參考:Python read,readline,readlines和大文件讀取

def tail(filepath, n, block=-1024):
    with open(filepath, 'rb') as f:
        f.seek(0,2)
        filesize = f.tell()
        while True:
            if filesize >= abs(block):
                f.seek(block, 2)
                s = f.readlines()
                if len(s) > n:
                    return s[-n:]
                    break
                else:
                    block *= 2
            else:
                block = -filesize


if __name__ == '__main__':
    lines = tail('million_line_file.txt', 10)
    for line in lines:
        print(line)

注意:只有用b二進制的方式打開文件,才可以從后往前讀!!!seek()方法才能接受負數參數

方法2 使用linecache:

參考:Python讀取大文件的最后N行

import linecache

# 放入緩存防止內存過載
def get_line_count(filename):
    count = 0
    with open(filename, 'r') as f:
        while True:
            buffer = f.read(1024 * 1)
            if not buffer:
                break
            count += buffer.count('\n')
    return count


if __name__ == '__main__':
    # 讀取最后30行
    file = 'million_line_file.txt'
    n = 30
    linecache.clearcache()
    line_count = get_line_count(file)
    print('num: ', line_count)
    line_count = line_count - 29
    for i in range(n):
        last_line = linecache.getline(file, line_count)
        print(line_count, last_line)
        line_count += 1

經測試,寫入一個簡單的一千萬行的txt文件,在老的macbookpro上需要15-20秒,
使用這個方法,讀取這個文件最后30行,只需要5秒左右。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM