如何使用 Python 高效地以逆序讀取文件
以逆序讀取文件,從最後一行開始回到開頭,Python提供了一個強大的解決方案:一個反向迭代各行的生成器函數
高效的生成器解決方案:
下面的生成器函數,reverse_readline,有效率地完成了這個任務:
import os def reverse_readline(filename, buf_size=8192): """A generator that returns the lines of a file in reverse order""" with open(filename, 'rb') as fh: segment = None offset = 0 fh.seek(0, os.SEEK_END) file_size = remaining_size = fh.tell() while remaining_size > 0: offset = min(file_size, offset + buf_size) fh.seek(file_size - offset) buffer = fh.read(min(remaining_size, buf_size)) # remove file's last "\n" if it exists, only for the first buffer if remaining_size == file_size and buffer[-1] == ord('\n'): buffer = buffer[:-1] remaining_size -= buf_size lines = buffer.split('\n'.encode()) # append last chunk's segment to this chunk's last line if segment is not None: lines[-1] += segment segment = lines[0] lines = lines[1:] # yield lines in this chunk except the segment for line in reversed(lines): # only decode on a parsed line, to avoid utf-8 decode error yield line.decode() # Don't yield None if the file was empty if segment is not None: yield segment.decode()
這個函數維護偏移量並從末尾開始以反向區塊讀取檔案。它以相反的順序產生行,同時處理最後一行可能有尾隨換行符的特殊情況。
要使用此生成器,只需以二進位模式開啟檔案並以相反的順序迭代各行:
for line in reverse_readline("my_file.txt"): # Process line in reverse order
以上是如何在Python中有效率地向後讀取檔案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!