Seek & Tell-Notes
Seek & Tell-Notes
Used to change the position of the file handle(file pointer) to a given specific position.
File pointer is like a cursor that defines from where the data has to be read or written in
the file.
Seek() can be done in 2 ways:
1. Absolute Positioning
2. Relative Positioning
Absolute Positioning
Gives the file pointer has to position itself.
Syntax: f.seek(<file_location>)
Example: f.seek(20)
The above statement moves the file pointer to 20th byte in the file from the beginning.
Text files can only seek from the beginning of the file. To overcome this, we can open the
file in binary mode.
Relative Positioning
Syntax:
f.seek(offset,from_where) # f is the filehandle or file pointer.
from_where arguments can have 3 types of values:
* 0: sets the file pointer from the beginning of the file.(By default, the value for from_where is ‘0’).
* 1: sets the file pointer from the current position of the file.
* 2: sets the file pointer from the end of the file.
Example:
f.seek(-10,1) from current position, move 10 bytes backward.
f.seek(10,1) from current position, move 10 bytes forward.
f.seek(10,0) from beginning of file, move 10 bytes forward.
Seek() with negative offset only works when the file is opened in binary mode.
tell():
It returns the current position of the file pointer within the file.
If we move the file pointer through seek(), tell() is used to tell the position where file pointer is
currently pointing to.
Syntax: f.tell()
Example for open the file in text mode:
f=open("sample.txt","r")
f.seek(2)
print(f.read(5))
print("Current position of pointer=",f.tell())
f.seek(4)
print(f.read())
print("Current position of pointer=",f.tell())
Output
Example for open the file in binary mode:
f=open("sample.txt","rb")
f.seek(2)
print(f.read(5))
print("Current position of pointer=",f.tell())
f.seek(4,1)
print(f.read(10))
print("Current position of pointer=",f.tell())
Example for reading data from the end of the file:
f=open("sample.txt","rb")
f.seek(-5,2)
print(f.read(3))
print("Current position of pointer=",f.tell())
Output