Existing answers do answer the question, but do not provide a solution.
From readthedocs :
If the file is opened in text mode (without b ), only offsets returned by the tell() function are allowed. Using other offsets causes undefined behavior.
This is confirmed by the documentation , which states:
In text files (which open without b in the mode line), only search is allowed relative to the beginning of the file [ os.SEEK_SET ] ...
This means that if you have this code from old Python:
f.seek(-1, 1)
it will look like this in Python 3:
f.seek(f.tell() - 1, os.SEEK_SET)
Decision
Combining this information, we can achieve the goal of OP:
f.seek(0, os.SEEK_END) # seek to end of file; f.seek(0, 2) is legal f.seek(f.tell() - 3, os.SEEK_SET) # go backwards 3 bytes
Eric Lindsey Jul 02 '18 at 7:41 2018-07-02 07:41
source share