python head, tail and backward read by lines of a text file

前端 未结 3 729
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-07 19:21

How to implement somethig like the \'head\' and \'tail\' commands in python and backward read by lines of a text file?

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-07 20:05

    Tail:

    def tail(fname, lines):
        """Read last N lines from file fname."""
        f = open(fname, 'r')
        BUFSIZ = 1024
        f.seek(0, os.SEEK_END)
        fsize = f.tell()
        block = -1
        data = ""
        exit = False
        while not exit:
            step = (block * BUFSIZ)
            if abs(step) >= fsize:
                f.seek(0)
                exit = True
            else:
                f.seek(step, os.SEEK_END)
            data = f.read().strip()
            if data.count('\n') >= lines:
                break
            else:
                block -= 1
        return data.splitlines()[-lines:]
    

提交回复
热议问题