How to read a file in reverse order using python? I want to read a file from last line to first line.
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
You can also use python module
file_read_backwards
.After installing it, via
pip install file_read_backwards
(v1.2.1), you can read the entire file backwards (line-wise) in a memory efficient manner via:It supports "utf-8","latin-1", and "ascii" encodings.
Support is also available for python3. Further documentation can be found at http://file-read-backwards.readthedocs.io/en/latest/readme.html
Here you can find my my implementation, you can limit the ram usage by changing the "buffer" variable, there is a bug that the program prints an empty line in the beginning.
And also ram usage may be increase if there is no new lines for more than buffer bytes, "leak" variable will increase until seeing a new line ("\n").
This is also working for 16 GB files which is bigger then my total memory.
If you are on linux, you can use
tac
command.2 recipes you can find in ActiveState here and here
And in Python 3:
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?