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
A correct, efficient answer written as a generator.
Most of the answers need to read the whole file before doing anything. This sample reads increasingly large samples from the end.
I only saw Murat Yükselen's answer while writing this answer. It's nearly the same, which I suppose is a good thing. The sample below also deals with \r and increases its buffersize at each step. I also have some unit tests to back this code up.
Thanks for the answer @srohde. It has a small bug checking for newline character with 'is' operator, and I could not comment on the answer with 1 reputation. Also I'd like to manage file open outside because that enables me to embed my ramblings for luigi tasks.
What I needed to change has the form:
I'd love to change to:
Here is a modified answer that wants a file handle and keeps newlines:
Read the file line by line and then add it on a list in reverse order.
Here is an example of code :
a simple function to create a second file reversed (linux only):
how to use