Search from end of file throwing unsupported exception

I have this piece of code, and I'm trying to search back from the end of the file using python:

f=open('D:\SGStat.txt','a'); f.seek(0,2) f.seek(-3,2) 

This throws the following exception during operation:

 f.seek(-3,2) io.UnsupportedOperation: can't do nonzero end-relative seeks 

Am I missing something here?

+19
python file
Feb 03 '14 at 17:14
source share
3 answers

From the documentation for Python 3.2 and later:

In text files (opened without line b in the mode line), only search relative to the beginning of the file is allowed (an exception is a search at the very end of the file with seek(0, 2) ).

Therefore, you can change your program to the following:

 f = open('D:\SGStat.txt', 'ab') f.seek(0, 2) f.seek(-3, 2) 

However, you should be aware that adding the flag b while reading or writing text can have unintended consequences (for example, with multibyte encoding) and actually changes the type of data being read or written . For a more detailed discussion of the cause of the problem and the solution, which does not require the addition of the b flag, see Another answer to this question .

+32
Feb 03 '14 at 17:21
source share

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) # seek -1 from current position 

it will look like this in Python 3:

 f.seek(f.tell() - 1, os.SEEK_SET) # os.SEEK_SET == 0 

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 
+17
Jul 02 '18 at 7:41
source share

To use the search from the current position and end, you need to open the text file in binary mode. Check out this example where I created the file "nums.txt" and put "ABCDEFGHIJKLMNOPQRSTUVWXYZ" in it. I read the letters of the string "PYTHON" from the file and display the same. Check out the code I'm running in Python 3.6 windows in Anaconda 4.2

  >>> file=open('nums.txt','rb') >>> file.seek(15,0) 15 >>> file.read(1).decode('utf-8') 'P' >>> file.seek(8,1) 24 >>> file.read(1).decode('utf-8') 'Y' >>> file.seek(-7,2) 19 >>> file.read(1).decode('utf-8') 'T' >>> file.seek(7,0) 7 >>> file.read(1).decode('utf-8') 'H' >>> file.seek(6,1) 14 >>> file.read(1).decode('utf-8') 'O' >>> file.seek(-2,1) 13 >>> file.read(1).decode('utf-8') 'N' 
+2
Nov 24 '17 at 6:55
source share



All Articles