Python tell method:
The tell() method of IOBase class returns the current position of a file stream. In other words, the tell() method returns an integer value to indicate the position of the file stream.
Method Signature
The signature for the tell()
method is as shown below.
fileObject.tell()
Method parameters and return type
- Here, the tell() method doesn’t take any parameter.
- However, it will return an integer value.
Python tell() method Examples:
Example 1: In this case, we will open a file in w+ mode and check its cursor position after reading some bytes.
# Opening a file
f1 = open("test.txt", "w+")
# Writing
f1.write("Hello World")
f1.write("\nPython Programming")
# Checking current position
print("Current cursor position",f1.tell())
#Using seek to move cursor
print("Moving cursor to location ",f1.seek(6))
#Reading 5 bytes
print("Reading 5 bytes -------",f1.read(5))
#Checking current cursor position
print("Current cursor position",f1.tell())
# closing
f1.close()
Output
Current cursor position 30
Moving cursor to location 6
Reading 5 bytes ------- World
Current cursor position 11
Example 2: In this case, we will open a file in reading mode and check its current cursor position using the tell method.
# Opening a file
f1 = open("test.txt", "r")
#Using tell() method
print("Before reading - Current Position ",f1.tell())
# Reading
print(f1.read())
Using tell() method
print("After Reading - Current Position ",f1.tell())
# closing
f1.close()
Output
Before reading - Current Position 0
Welcome to the world of Java Programming
After Reading - Current Position 40
Is file <_io.TextIOWrapper name='test.txt' mode='r' encoding='UTF-8'> tell? True
Example 3: In this case, we will replace the word Java with python in a file.
#Opening and writing
f=open("python.txt","w+")
f.write("Welcome to the world of Java Programming")
#Using tell() method
print("Current Position ",f.tell())
#Moving cursor to word "Java"
f.seek(24,0)
#Reading line and storing in string
s=f.readline()
#Replacing string
s=s.replace('Java', 'Python')
#Using tell() method
f.seek(24,0)
print("Verifying Current Position ",f.tell())
f.write(s)
#Reading the file from beginning
f.seek(0)
print("After Updation --",f.read())
f.close()
Output
Current Position 40
Verifying Current Position 24
After Updation -- Welcome to the world of Python Programming
Conclusion
Hence, the tell() method returns an integer value representing a current position in a file stream.
References
Happy Learning 🙂