I am currently learning Python 3 with the Zed Shaw's book, Learning Python 3 The Hard Way.
When doing exercise 20 about functions and files, you get tasked with researcher what does the seek function does. By searching online I've come across with a couple of concepts regarding this function that I'm having trouble getting my head around:
Here's an explanation I've found online about seek()'s purpose:
Python file method seek() sets the file's current position at the offset.
- Under this context, what would "The file's current position" mean?
Here's an explanation I've found online about tell()'s purpose:
Python file method tell() returns the current position of the file read/write pointer within the file.
- Under this context, what would "The file read/write pointer" mean?
You can think of a file as a sequence of bytes (at least that is the case if you open up the file as a binary file using
mode='rb'
), similar to abytearray
stored on disk. When you first open the file withmode='rb'
, you are currently positioned or "pointing" at the beginning of the file, at offset 0, meaning that if you issue aread
forn
bytes you will be reading in the firstn
bytes of the file (assuming the file has at leastn
bytes worth of data). After the read your new file position is at offsetn
. So if you do nothing but issue successiveread
calls, you will read the file sequentially.Method
tell
returns your current "position", meaning simply your current offset within the file:Method
seek
allows you to change your current position in the file: