Product SiteDocumentation Site

10.6. Random seeking in a file

You can also randomly move around inside a file using seek() method. It takes two arguments , offset and whence. To know more about it let us read what python help tells us
seek(...) seek(offset[, whence]) -> None. Move to new file position. Argument offset is a byte count. Optional argument whence defaults to 0 (offset from start of file, offset should be >= 0); other values are 1 (move relative to current position, positive or negative), and 2 (move relative to end of file, usually negative, although many platforms allow seeking beyond the end of a file). If the file is opened in text mode, only offsets returned by tell() are legal. Use of other offsets causes undefined behavior. Note that not all file objects are speakable.
Let us see one example

>>> f = open('tempfile', 'w')
>>> f.write('0123456789abcdef')
>>> f.close()
>>> f = open('tempfile')
>>> f.tell()    #tell us the offset position
0L
>>> f.seek(5) # Goto 5th byte
>>> f.tell()
5L
>>> f.read(1) #Read 1 byte
'5'
>>> f.seek(-3, 2) # goto 3rd byte from the end
>>> f.read() #Read till the end of the file
'def'