Issue
I have this code snippet and I'm trying to seek backwards from the end of file using python:
f=open('D:\SGStat.txt','a');
f.seek(0,2)
f.seek(-3,2)
This throws the following exception while running:
f.seek(-3,2)
io.UnsupportedOperation: can't do nonzero end-relative seeks
Am i missing something here?
Solution
From the documentation for Python 3.2 and up:
In text files (those opened without a
b
in 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)
).
This is because text files do not have a 1-to-1 correspondence between encoded bytes and the characters they represent, so seek
can't tell where to jump to in the file to move by a certain number of characters.
If your program is okay with working in terms of raw bytes, you can change your program to read:
f = open('D:\SGStat.txt', 'ab')
f.seek(-3, 2)
Note the b
in the mode string, for a binary file. (Also note the removal of the redundant f.seek(0, 2)
call.)
However, you should be aware that adding the b
flag when you are reading or writing text can have unintended consequences (with multibyte encoding for example), and in fact changes the type of data read or written.
Answered By - jonrsharpe
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.