How to read a file in reverse order?

前端 未结 21 2532
礼貌的吻别
礼貌的吻别 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:41

    def previous_line(self, opened_file):
            opened_file.seek(0, os.SEEK_END)
            position = opened_file.tell()
            buffer = bytearray()
            while position >= 0:
                opened_file.seek(position)
                position -= 1
                new_byte = opened_file.read(1)
                if new_byte == self.NEW_LINE:
                    parsed_string = buffer.decode()
                    yield parsed_string
                    buffer = bytearray()
                elif new_byte == self.EMPTY_BYTE:
                    continue
                else:
                    new_byte_array = bytearray(new_byte)
                    new_byte_array.extend(buffer)
                    buffer = new_byte_array
            yield None
    

    to use:

    opened_file = open(filepath, "rb")
    iterator = self.previous_line(opened_file)
    line = next(iterator) #one step
    close(opened_file)
    

提交回复
热议问题