简体   繁体   中英

How does Python's seek function work?

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

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

What does seek do? Does is start at the beginning of the file and read loc-10 bytes? Or is it smart enough just to back up 10 bytes?

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

According to Python 2.7's docs :

file.seek(offset[, whence])

Set the file's current position, like stdio's fseek(). The whence argument is optional and defaults to os.SEEK_SET or 0 (absolute file positioning); other values are os.SEEK_CUR or 1 (seek relative to the current position) and os.SEEK_END or 2 (seek relative to the file's end).

Say you would want to go 10 bytes back relative to your position:

file.seek(-10, 1)

It should be smart enough to just back up 10 bytes, but I suppose that the details really depend on the filesystem/OS/runtime library you're using.

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

F.seek(-10,1)
file.seek() set the current read/write position.
file.tell() Returns the file's current position.

So when you did **loc = F.tell()** you are store the current file position to the loc variable.

And **file.seek()** takes two arguments **file.seek(offset, from)**

So you need to define from where to you want offset the file. **from** takes one of following values 0,1,2 (0 = beginning, 1 = current, 2 = end)

So that's how it's work.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM