How to read a file in reverse order?

前端 未结 21 2430
礼貌的吻别
礼貌的吻别 2020-11-22 04:51

How to read a file in reverse order using python? I want to read a file from last line to first line.

21条回答
  •  有刺的猬
    2020-11-22 05:31

    How about something like this:

    import os
    
    
    def readlines_reverse(filename):
        with open(filename) as qfile:
            qfile.seek(0, os.SEEK_END)
            position = qfile.tell()
            line = ''
            while position >= 0:
                qfile.seek(position)
                next_char = qfile.read(1)
                if next_char == "\n":
                    yield line[::-1]
                    line = ''
                else:
                    line += next_char
                position -= 1
            yield line[::-1]
    
    
    if __name__ == '__main__':
        for qline in readlines_reverse(raw_input()):
            print qline
    

    Since the file is read character by character in reverse order, it will work even on very large files, as long as individual lines fit into memory.

提交回复
热议问题