How to read a file in reverse order?

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

    import re
    
    def filerev(somefile, buffer=0x20000):
      somefile.seek(0, os.SEEK_END)
      size = somefile.tell()
      lines = ['']
      rem = size % buffer
      pos = max(0, (size // buffer - 1) * buffer)
      while pos >= 0:
        somefile.seek(pos, os.SEEK_SET)
        data = somefile.read(rem + buffer) + lines[0]
        rem = 0
        lines = re.findall('[^\n]*\n?', data)
        ix = len(lines) - 2
        while ix > 0:
          yield lines[ix]
          ix -= 1
        pos -= buffer
      else:
        yield lines[0]
    
    with open(sys.argv[1], 'r') as f:
      for line in filerev(f):
        sys.stdout.write(line)
    

提交回复
热议问题