seek() and tell() Functions in Python Programming

Note: Like other programming languages C, C++, Python, Java etc. Python also supports concept of file handling.

Please refer the below articles the understand the basic concepts of File Handling.

file-handling-in-python-programming

tell(): In python programming, within file handling concept tell() function is used to get the actual position of file object. By file object we mean a cursor. And it’s cursor, who decides from where data has to be read or written in a file.

Syntax:

f.tell()
#here f is file handler or file object


Example 1:

tell-function-in-python-file-handlingExplanation: We opened “test.txt” file in read mode. If file opened in read mode than by default file object or file pointer at beginning ie. 0 position. Hence our output is 0. You can also see in above image (data written in text file) highlighted in yellow that pointer is at beginning.

seek(): 
In python programming, within file handling concept seek() function is used to shift/change the position of file object to required position. By file object we mean a cursor. And it’s cursor, who decides from where data has to be read or write in a file.

Syntax:

f.seek(offset)
#here f is file handler or file object
#here offset is postions to move forward


Example 1:

seek-function-in-python

Explanation: We opened “test.txt” file in read mode. If file opened in read mode than by default file object or file pointer at beginning ie. 0 position. But here we used seek() function and set its position to 6. It means now our pointer has gone to sixth position, if we start reading then it will start reading from sixth character. Hence our output is “there how are you?”. You can also see in above image (data written in text file) highlighted in yellow that “hello” is skipped because pointer is moved to sixth character using seek() function.


That’s all about the seek() and tell() function….