Python documentation says:
In text files (those opened without a
bin the mode string), only seeks relative to the beginning of the file are allowed (the exception being seeking to the very file end withseek(0, 2)).
And indeed, this fails:
with open(filename, 'rt') as f:
f.seek(2, os.SEEK_SET)
f.seek(2, os.SEEK_CUR)
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
io.UnsupportedOperation: can't do nonzero cur-relative seeks
The Question
I can easily replace every f.seek(offset, os.SEEK_CUR) with f.seek(f.tell() + offset, os.SEEK_SET), so, why doesn't Python do it itself?
This works:
with open(filename, 'rt') as f:
f.seek(2, os.SEEK_SET)
f.seek(f.tell() + 2, os.SEEK_SET)
Am I missing something? Will this fail sometimes? What should I be careful about?
I can imagine problems with seeking into the middle of a multi-byte UTF-8 sequence, but I don't see how it makes a difference whether I seek from SEEK_SET or SEEK_CUR.