Free cookie consent management tool by TermsFeed The tell() method of the TextIOWrapper class in Python | Pythontic.com

The tell() method of the TextIOWrapper class in Python

Overview:

  • The method tell() of the TextIOWrapper class returns the position of the stream pointer in the underlying buffer. 

Example:

The Python example uses the obtained stream pointer later while restarting the write operation at the end of the buffer. 

# Example Python program that obtains the 
# stream position using the method tell() from 
# the TextIOWrapper class of the io module. 
# The same position is used in the subsequent
# call to the seek() method.
import io

# Using TextIOWrapper write to a buffer
buffer = io.BytesIO()
textIOWrapper = io.TextIOWrapper(buffer)
textIOWrapper.write("This is a simple sentence.")

# Store the current position in the stream
pos = textIOWrapper.tell()
print(pos)
textIOWrapper.flush()

# Reset the stream position  
textIOWrapper.seek(0, io.SEEK_SET)

# Read contents
text = textIOWrapper.read(1024)
print(text)

# Go to the previous stream position 
# and write some content
textIOWrapper.seek(pos, io.SEEK_SET)
textIOWrapper.write("This is not a complex sentence.")
textIOWrapper.flush()

# Read from the beginning
textIOWrapper.seek(0, io.SEEK_SET)
text = textIOWrapper.read(1024)
print(text)

Output:

26
This is a simple sentence.
This is a simple sentence.This is not a complex sentence.

 


Copyright 2025 © pythontic.com