How does the Python function work?

If I have a file-like object and do the following:

F = open('abc', 'r') ... loc = F.tell() F.seek(loc-10) 

What do we have to do? Does the start start at the beginning of the file and read loc-10 bytes? Or is he smart enough to back up 10 bytes?

+6
source share
4 answers

These are OS- and libc-specific. the file.seek() operation is delegated to the fseek(3) C call for the actual OS level files.

+9
source

According to Python 2.7 docs :

file.seek(offset[, whence])

Set the current file position, for example, fseek () stdio. From where the argument is optional and the default is os.SEEK_SET or 0 (absolute file positioning); other values ​​are os.SEEK_CUR or 1 (search relative to the current position) and os.SEEK_END or 2 (search the end with respect to files).

Suppose you would like to leave 10 bytes relative to your position:

 file.seek(-10, 1) 
+8
source

It should be smart enough to just back up 10 bytes, but I suppose the details really depend on the file system library / operating system / runtime you are using.

Note that if you just want to back up 10 bytes, there is no need to tell .

 F.seek(-10,1) 
+4
source

according to the documentation you need to do f.seek(offset, from_what) or in your case F.seek(-10, loc)

your example should work, but this is more explicit

-4
source

All Articles