Home »
Python
Python | Read file from given index (Example of tell() and seek())
In this tutorial, we are going to learn about two important methods of python file handling – tell() and seek(), here we will learn how to set file pointer position at a specific position and how to read content from there?
By Pankaj Singh Last updated : September 17, 2023
In Python, to read a file from the given index, you need to use mainly two methods tellg() and seek() of the File object.
tell() Method
This method returns the current position of file pointer within the file.
Syntax
file_object.tell()
seek() Method
It set the position of file pointer at a specific position.
Syntax
file_object.seek(offset, whence)
Here,
- offset is the position of read/write pointer of the file.
-
whence is an optional argument, it has 3 values
- 0 – to seek the file pointer from current position
- 1 – to seek the file pointer from starting position of the file
- 2 – to seek the file pointer from ending position of the file
Python program to read file from given index
def main():
# Writing a file
fo = open("data.txt", "wt")
fo.write("Hello world, how are you? Here, you are learning python")
fo.close()
# Opening a file in read mode
fo = open("data.txt", "r")
print("Name of the File : ", fo.name)
# reading content
str = fo.read(10)
print("Read String is till 10 : ", str)
pos = fo.tell()
print("Current Position : ", pos)
str = fo.read(10)
print("Read String is till next 10 : ", str)
pos = fo.tell()
print("Current Position : ", pos)
print()
print("Sending Pointer back to Top")
pos = fo.seek(0, 0)
print("Current Position : ", pos)
str = fo.read(25)
print("Read String is till 25 : ", str)
pos = fo.tell()
print("Current Position : ", pos)
fo.close()
if __name__ == "__main__":
main()
Output
The output of the above program is:
Name of the File : data.txt
Read String is till 10 : Hello worl
Current Position : 10
Read String is till next 10 : d, how are
Current Position : 20
Sending Pointer back to Top
Current Position : 0
Read String is till 25 : Hello world, how are you?
Current Position : 25