Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Python's seek function work?

Tags:

python

seek

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?

like image 616
jlconlin Avatar asked Nov 07 '12 21:11

jlconlin


4 Answers

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

like image 125
Ignacio Vazquez-Abrams Avatar answered Sep 23 '22 14:09

Ignacio Vazquez-Abrams


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)
like image 42
TankorSmash Avatar answered Sep 23 '22 14:09

TankorSmash


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)
like image 27
mgilson Avatar answered Sep 23 '22 14:09

mgilson


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.

like image 32
Ayemun Hossain Ashik Avatar answered Sep 22 '22 14:09

Ayemun Hossain Ashik