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
Accepted answer won't work for cases with large files that won't fit in memory (which is not a rare case).
As it was noted by others, @srohde answer looks good, but it has next issues:
even if we refactor to accept file object, it won't work for all encodings: we can choose file with
utf-8
encoding and non-ascii contents likepass
buf_size
equal to1
and will haveof course text may be larger but
buf_size
may be picked up so it'll lead to obfuscated error like above,So considering all these concerns I've written separate functions:
First of all let's define next utility functions:
ceil_division
for making division with ceiling (in contrast with standard//
division with floor, more info can be found in this thread)split
for splitting string by given separator with ability to keep it:read_batch_from_end
to read batch from the right end of binary streamAfter that we can define function for reading byte stream in reverse order like
and finally a function for reversing text file can be defined like:
Tests
Preparations
I've generated 4 files using
fsutil
command:also I've refactored @srohde solution to work with file object instead of file path.
Test script
Note: I've used
collections.deque
class to exhaust generator.Outputs
For PyPy 3.5 on Windows 10:
For CPython 3.5 on Windows 10:
So as we can see it performs like original solution, but is more general and free of its disadvantages listed above.
Advertisement
I've added this to
0.3.0
version oflz
package (requires Python 3.5+) that have many well-tested functional/iterating utilities.Can be used like
It supports all standard encodings (maybe except
utf-7
since it is hard for me to define a strategy for generating strings encodable with it).Always use
with
when working with files as it handles everything for you:Or in Python 3:
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
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
How about something like this:
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.