How to read a file in reverse order using python? I want to read a file from last line to first line.
Read the file line by line and then add it on a list in reverse order.
Here is an example of code :
reverse = []
with open("file.txt", "r") as file:
for line in file:
line = line.strip()
reverse[0:0] = line
I don't think this has been mentioned before, but using deque
from collections
and reverse
works for me:
from collections import deque
fs = open("test.txt","rU")
fr = deque(fs)
fr.reverse() # reverse in-place, returns None
for li in fr:
print li
fs.close()
If you are concerned about file size / memory usage, memory-mapping the file and scanning backwards for newlines is a solution:
How to search for a string in text files?
Always use with
when working with files as it handles everything for you:
with open('filename', 'r') as f:
for line in reversed(f.readlines()):
print line
Or in Python 3:
with open('filename', 'r') as f:
for line in reversed(list(f.readlines())):
print(line)
I had to do this some time ago and used the below code. It pipes to the shell. I am afraid i do not have the complete script anymore. If you are on a unixish operating system, you can use "tac", however on e.g. Mac OSX tac command does not work, use tail -r. The below code snippet tests for which platform you're on, and adjusts the command accordingly
# 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)
A correct, efficient answer written as a generator.
import os
def reverse_readline(filename, buf_size=8192):
"""A generator that returns the lines of a file in reverse order"""
with open(filename) as fh:
segment = None
offset = 0
fh.seek(0, os.SEEK_END)
file_size = remaining_size = fh.tell()
while remaining_size > 0:
offset = min(file_size, offset + buf_size)
fh.seek(file_size - offset)
buffer = fh.read(min(remaining_size, buf_size))
remaining_size -= buf_size
lines = buffer.split('\n')
# The first line of the buffer is probably not a complete line so
# we'll save it and append it to the last line of the next buffer
# we read
if segment is not None:
# If the previous chunk starts right from the beginning of line
# do not concat the segment to the last line of new chunk.
# Instead, yield the segment first
if buffer[-1] != '\n':
lines[-1] += segment
else:
yield segment
segment = lines[0]
for index in range(len(lines) - 1, 0, -1):
if lines[index]:
yield lines[index]
# Don't yield None if the file was empty
if segment is not None:
yield segment