Error using seek() method: can't do nonzero end-relative seeks

The seek() method in python file operations:

grammar

The seek() method syntax is as follows:

fileObject.seek(offset[, whence])

parameter

  • offset  -- the starting offset, that is, the number of bytes that need to move the offset

  • whence: optional, the default value is 0. Give a definition to the offset parameter, indicating where to start the offset; 0 means starting from the beginning of the file, 1 means starting from the current position, and 2 means starting from the end of the file.

return value

The function has no return value.


When using the seek() function, sometimes an error will be reported as "io.UnsupportedOperation: can't do nonzero cur-relative seeks", the code is as follows:

copy code
>>> f=open("aaa.txt","r+") #Open the file aaa.txt in read-write format
>>> f.read() #Read the file content
'my name is liuxiang,i am come frome china'
>>> f.seek(3,0) #Offset three units from the beginning (offset to "n")
3
>>> f.seek(5,1) #Want to offset 5 units from the last offset position (ie "n")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
io.UnsupportedOperation: can't do nonzero cur-relative seeks
copy code

It stands to reason that according to the format file.seek(offset, when) of the seek() method, the following 1 represents the offset from the current position, so why is an error reported?

This is because, in text files, there is no file opened with the b-mode option, only relative positions are allowed to be calculated from the beginning of the file, and an exception will be thrown when calculating from the end of the file. Change f=open("aaa.txt","r+") to

f = open("aaa.txt","rb") will do

 

The corrected code is as follows:

>>> f = open("aaa.txt","rb")
>>> f.seek(3,0)
3
>>> f.seek(5,1)
8

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326527604&siteId=291194637