python按格式读_使用python按相反顺序读取文件

545863cd0001b72a02200220-100-100.jpg

狐的传说

写成生成器的正确、有效的答案。import osdef reverse_readline(filename, buf_size=8192):

    """A generator that returns the lines of a file in reverse order"""

    with open(filename) 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))

            remaining_size -= buf_size

            lines = buffer.split('\n')

            # The first line of the buffer is probably not a complete line so

            # we'll save it and append it to the last line of the next buffer

            # we read

            if segment is not None:

                # If the previous chunk starts right from the beginning of line

                # do not concat the segment to the last line of new chunk.

                # Instead, yield the segment first 

                if buffer[-1] != '\n':

                    lines[-1] += segment                else:

                    yield segment

            segment = lines[0]

            for index in range(len(lines) - 1, 0, -1):

                if lines[index]:

                    yield lines[index]

        # Don't yield None if the file was empty

        if segment is not None:

            yield segment

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值