seek() and tell() Functions in Python Programming
tell()
* In python programming, within file handling concepts 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()
#where f is file handler or file object
Example:
f=open(“test.txt”,”r”)
x=f.tell()
print(x)
Output:
0
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. Hence our output is 0.
seek()
* In python programming, within file handling concepts 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 positions to move forward
Example:
f=open(“test.txt”,”r”)
#1
x=f.tell()
print(x)
print(f.read())
#2
f.seek(6)
x=f.tell()
print(x)
print(f.read())
Explanation:
#1
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.
here we print x=f.tell() it gives us 0 (zero)
and when we read the file it gives the full contents of the file.
#2
But now 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.
here we print x=f.tell() it gives us 6
and when we read the file it gives the full contents of the file from 6th character onwards.