How to read lines from a file in python starting from the end

前端 未结 5 1518
轮回少年
轮回少年 2020-11-30 12:58

I need to know how to read lines from a file in python so that I read the last line first and continue in that fashion until the cursor reach\'s the beginning of the file. A

5条回答
  •  -上瘾入骨i
    2020-11-30 13:25

    A straightforward way is to first create a temporary reversed file, then reversing each line in this file.

    import os, tempfile
    
    def reverse_file(in_filename, fout, blocksize=1024):
        filesize = os.path.getsize(in_filename)
        fin = open(in_filename, 'rb')
        for i in range(filesize // blocksize, -1, -1):
            fin.seek(i * blocksize)
            data = fin.read(blocksize)
            fout.write(data[::-1])
    
    def enumerate_reverse_lines(in_filename, blocksize=1024):
        fout = tempfile.TemporaryFile()
        reverse_file(in_filename, fout, blocksize=blocksize)
        fout.seek(0)
        for line in fout:
            yield line[::-1]
    

    The above code will yield lines with newlines at the beginning instead of the end, and there is no attempt to handle DOS/Windows-style newlines (\r\n).

提交回复
热议问题