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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With