在 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 循环中:
for line in reverse_readline('myfile.txt'): print(line)
这将以相反的顺序打印文件的行。
以上是如何使用Python高效逆序读取大文件?的详细内容。更多信息请关注PHP中文网其他相关文章!