How to read a file in reverse order?

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

    Here you can find my my implementation, you can limit the ram usage by changing the "buffer" variable, there is a bug that the program prints an empty line in the beginning.

    And also ram usage may be increase if there is no new lines for more than buffer bytes, "leak" variable will increase until seeing a new line ("\n").

    This is also working for 16 GB files which is bigger then my total memory.

    import os,sys
    buffer = 1024*1024 # 1MB
    f = open(sys.argv[1])
    f.seek(0, os.SEEK_END)
    filesize = f.tell()
    
    division, remainder = divmod(filesize, buffer)
    line_leak=''
    
    for chunk_counter in range(1,division + 2):
        if division - chunk_counter < 0:
            f.seek(0, os.SEEK_SET)
            chunk = f.read(remainder)
        elif division - chunk_counter >= 0:
            f.seek(-(buffer*chunk_counter), os.SEEK_END)
            chunk = f.read(buffer)
    
        chunk_lines_reversed = list(reversed(chunk.split('\n')))
        if line_leak: # add line_leak from previous chunk to beginning
            chunk_lines_reversed[0] += line_leak
    
        # after reversed, save the leakedline for next chunk iteration
        line_leak = chunk_lines_reversed.pop()
    
        if chunk_lines_reversed:
            print "\n".join(chunk_lines_reversed)
        # print the last leaked line
        if division - chunk_counter < 0:
            print line_leak
    

提交回复
热议问题