Hi,
How to read a file in reverse order using python? I want to read a file from last line to first line. Any one can help me?
Thanks in advance, Nimmy
Hi,
How to read a file in reverse order using python? I want to read a file from last line to first line. Any one can help me?
Thanks in advance, Nimmy
for line in reversed(open("filename").readlines()):
    print line.rstrip()
for line in reversed(open("file").readlines()):
    print line.rstrip()
If you are on linux, you can use tac command.
$ tac file
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)
If you are on Mac OSX tac command does not work, use tail -r
# We need a command to reverse the line order of the file. On Linux this
# is 'tac', on OSX it is 'tail -r'
# 'tac' is not supported on osx, 'tail -r' is not supported on linux.
if sys.platform == "darwin":
    command += "|tail -r"
elif sys.platform == "linux2":
    command += "|tac"
else:
    raise EnvironmentError('Platform %s not supported' % sys.platform)
I've posted an answer that reads the file incrementally, in response to Most efficient way to search the last x lines of a file in python.