在Python中逆序读取文件
当需要处理文件末尾的数据时,就需要以相反的顺序读取文件。在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()
用法
要使用reverse_readline生成器,请打开一个文件以二进制模式读取并以相反的顺序迭代各行:
with open('input.txt', 'rb') as input_file: for line in reverse_readline(input_file): # Process line in reverse order
以上是如何使用Python逆序读取文件?的详细内容。更多信息请关注PHP中文网其他相关文章!