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

前端 未结 5 1521
轮回少年
轮回少年 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条回答
  •  旧巷少年郎
    2020-11-30 13:08

    This solution is simpler than any others I've seen.

    def xreadlines_reverse(f, blksz=524288):
        "Act as a generator to return the lines in file f in reverse order."
        buf = ""
        f.seek(0, 2)
        pos = f.tell()
        lastn = 0
        if pos == 0:
            pos = -1
        while pos != -1:
            nlpos = buf.rfind("\n", 0, -1)
            if nlpos != -1:
                line = buf[nlpos + 1:]
                if line[-1] != "\n":
                    line += "\n"
                buf = buf[:nlpos + 1]
                yield line
            elif pos == 0:
                pos = -1
                yield buf
            else:
                n = min(blksz, pos)
                f.seek(-(n + lastn), 1)
                rdbuf = f.read(n)
                lastn = len(rdbuf)
                buf = rdbuf + buf
                pos -= n
    

    Example usage:

    for line in xreadlines_reverse(open("whatever.txt")):
        do_stuff(line)
    

提交回复
热议问题