问题
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?
回答1:
It is OS- and libc-specific. the file.seek()
operation is delegated to the fseek(3)
C call for actual OS-level files.
回答2:
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)
回答3:
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)
回答4:
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.
回答5:
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
来源:https://stackoverflow.com/questions/13278748/how-does-pythons-seek-function-work