使用python以相反的顺序读取文件

发布于 2021-02-02 23:19:13

如何使用python以相反的顺序读取文件?我想从最后一行读取文件。

关注者
0
被浏览
68
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。
    for line in reversed(open("filename").readlines()):
        print line.rstrip()
    

    在Python 3中:

    for line in reversed(list(open("filename"))):
        print(line.rstrip())
    


  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    作为生成器编写的正确,有效的答案。

    import os
    
    def 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
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看