How to read a file in reverse order?

前端 未结 21 2560
礼貌的吻别
礼貌的吻别 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:31
    for line in reversed(open("filename").readlines()):
        print line.rstrip()
    

    And in Python 3:

    for line in reversed(list(open("filename"))):
        print(line.rstrip())
    
    0 讨论(0)
  • 2020-11-22 05:31

    How about something like this:

    import os
    
    
    def readlines_reverse(filename):
        with open(filename) as qfile:
            qfile.seek(0, os.SEEK_END)
            position = qfile.tell()
            line = ''
            while position >= 0:
                qfile.seek(position)
                next_char = qfile.read(1)
                if next_char == "\n":
                    yield line[::-1]
                    line = ''
                else:
                    line += next_char
                position -= 1
            yield line[::-1]
    
    
    if __name__ == '__main__':
        for qline in readlines_reverse(raw_input()):
            print qline
    

    Since the file is read character by character in reverse order, it will work even on very large files, as long as individual lines fit into memory.

    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-11-22 05:34
    import sys
    f = open(sys.argv[1] , 'r')
    for line in f.readlines()[::-1]:
        print line
    
    0 讨论(0)
  • 2020-11-22 05:37

    you would need to first open your file in read format, save it to a variable, then open the second file in write format where you would write or append the variable using a the [::-1] slice, completely reversing the file. You can also use readlines() to make it into a list of lines, which you can manipulate

    def copy_and_reverse(filename, newfile):
        with open(filename) as file:
            text = file.read()
        with open(newfile, "w") as file2:
            file2.write(text[::-1])
    
    0 讨论(0)
  • 2020-11-22 05:38
    for line in reversed(open("file").readlines()):
        print line.rstrip()
    

    If you are on linux, you can use tac command.

    $ tac file
    

    2 recipes you can find in ActiveState here and here

    0 讨论(0)
提交回复
热议问题