Use codecs.getreader to produce a wrapper object:

text_stream = codecs.getreader("utf-8")(bytes_stream)

Works on Python 2 and Python 3.

Answer from jbg on Stack Overflow
🌐
ProgramCreek
programcreek.com › python › example › 5779 › io.TextIOWrapper
Python Examples of io.TextIOWrapper
def _fopen(fname, mode): """ Extend file open function, to support 1) "-", which means stdin/stdout 2) "$cmd |" which means pipe.stdout """ if mode not in ["w", "r", "wb", "rb"]: raise ValueError("Unknown open mode: {mode}".format(mode=mode)) if not fname: return None fname = fname.rstrip() if fname == "-": if mode in ["w", "wb"]: return sys.stdout.buffer if mode == "wb" else sys.stdout else: return sys.stdin.buffer if mode == "rb" else sys.stdin elif fname[-1] == "|": pin = pipe_fopen(fname[:-1], mode, background=(mode == "rb")) return pin if mode == "rb" else TextIOWrapper(pin) else: if mode in ["r", "rb"] and not os.path.exists(fname): raise FileNotFoundError( "Could not find common file: {}".format(fname)) return open(fname, mode) ... def _python2_bz2open(fn, mode, encoding, newline): """Wrapper to open bz2 in text mode.
🌐
Python Morsels
pythonmorsels.com › TextIOWrapper
TextIOWrapper‽ converting files to strings in Python - Python Morsels
February 5, 2024 - Unfortunately, that just gives us back a generic string representation saying the object we've converted is an _io.TextIOWrapper object. ... Well, reading a file isn't an entirely trivial operation. In fact, when you read from a file, if you read the same file a second time, you'll see that it's empty: >>> file.read() 'This is an example text-based file.\nIt existed before we read it.\n' >>> file.read() ''
Discussions

How to access io.TextIOWrapper in python
found solution using Bing AI import io class Node: Id: int X: float Y: float Z: float def __init__(self, Id: int, x: float, y: float, z: float): self.Id = int(Id) self.X = float(x) self.Y = float(y) self.Z = float(z) def write(self, file:io.TextIOWrapper): file.write(f"{self.Id},{self.X:0.4f},{self.Y:0.4f},{self.Z:0.4f};\n") def __str__(self) -> str: return f"{self.Id}:{self.X},{self.Y},{self.Z}" More on reddit.com
🌐 r/learnpython
2
0
May 16, 2023
python 3.x - How can we create a `TextIOWrapper` instance? - Stack Overflow
Thanks. How do you a TextIOBase instance, which is not TextIOWrapper instance? More on stackoverflow.com
🌐 stackoverflow.com
What Is the Role of io.TextIOWrapper in Python Input Handling?
Python transforms file objects into an io.TextIOWrapper is used upon opening files with the default text mode feature of open(). This transformation allows smooth text data manipulation. The system transcends text format between different coding methods to create cross-program compatibility. During file reading operations, such as the following one: with open("example... More on mindstick.com
🌐 mindstick.com
0
March 29, 2025
Change class from '_io.TextIOWrapper' to 'bytes'
Hello Pythonic minds, I have an text file named “ex23_RawBytes_ConvertedToBytes.txt” These are just text with class ‘_io.TextIOWrapper’ when I checked type in python Any way I can convert them into bytes? The reason I am doing this is that I have all the raw bytes in text but their ... More on discuss.python.org
🌐 discuss.python.org
9
0
February 5, 2024
🌐
Beautiful Soup
tedboy.github.io › python_stdlib › generated › generated › io.TextIOWrapper.html
io.TextIOWrapper — Python Standard Library
io.TextIOWrapper · View page source · class io.TextIOWrapper¶ · Character and line based layer over a BufferedIOBase object, buffer. encoding gives the name of the encoding that the stream will be decoded or encoded with. It defaults to locale.getpreferredencoding.
🌐
Pythontic
pythontic.com › io › textiowrapper › introduction
The TextIOWrapper class in Python | Pythontic.com
Buffering refers to the technique of gathering some amount of bytes before writing it to the destination. TextIOWrapper gathers the contents up to the occurrence of a new line character before making a call to flush. Buffering can be turned-off if write_through is enabled. The example uses a BytesIO object as the underlying buffer.
🌐
Python Module of the Week
pymotw.com › 3 › io
io — Text, Binary, and Raw Stream I/O Tools
December 31, 2016 - ') wrapper.write('ÁÇÊ') # Retrieve the value written print(output.getvalue()) output.close() # discard buffer memory # Initialize a read buffer input = io.BytesIO( b'Inital value for read buffer with unicode characters ' + 'ÁÇÊ'.encode('utf-8') ) wrapper = io.TextIOWrapper(input, encoding='utf-8') # Read from the buffer print(wrapper.read()) This example uses a BytesIO instance as the stream.
🌐
Python
docs.python.org › 3 › library › io.html
io — Core tools for working with streams
The above implicitly extends to text files, since the open() function will wrap a buffered object inside a TextIOWrapper. This includes standard streams and therefore affects the built-in print() function as well. ... © Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
🌐
Reddit
reddit.com › r/learnpython › how to access io.textiowrapper in python
r/learnpython on Reddit: How to access io.TextIOWrapper in python
May 16, 2023 -

I am writing function to help me printing data in text files with different types. in my code for function def write(self, file:io.TextIOWrapper): i want to specify type of my file variable to improve my documentation and code readability. Any idea how to do this?

class Node:
    Id: int
    X: float
    Y: float
    Z: float

    def __init__(self, Id: int, x: float, y: float, z: float):
        self.Id = int(Id)
        self.X = float(x)
        self.Y = float(y)
        self.Z = float(z)

    def write(self, file:io.TextIOWrapper):
        file.write(f"{self.Id},{self.X:0.4f},{self.Y:0.4f},{self.Z:0.4f};\n")

    def __str__(self):
        return f"{self.Id}:{self.X},{self.Y},{self.Z}"
Find elsewhere
🌐
Drbeane
drbeane.github.io › python › pages › text_files.html
Working with Text Files — Python Programming
In the cell below, we open the file my_file.txt, storing the value returned into a variable named fin (which stands for file input). We then print the type of fin, and see that it has type _io.TextIOWrapper.
🌐
SICORPS
sicorps.com › h0me › python 3: understanding textiowrapper
Python 3: Understanding TextIOWrapper -
March 17, 2024 - In this example, we’re using `codecs_open()` to open the file and specify that it should be read using UTF-8 encoding (which is a common one). Then, we wrap the resulting file object in an io.TextIOWrapper instance so that Python knows how to handle line endings properly.
🌐
University of Toronto
cs.toronto.edu › ~guerzhoy › c4m_website_archive › workshops › W5 › Files and While Loops.html
Files and While Loops
This opens the file named story.txt from the current directory. It is open for reading (that's the r mode) and the type of object is io.TextIOWrapper. Don't stress about the type at all. Just think of it as an open file. The important conceptual idea here is that this object not only knows ...
🌐
Finxter
blog.finxter.com › home › learn python blog › converting python bytes to a textiowrapper object
Converting Python Bytes to a TextIOWrapper Object - Be on the Right Side of Change
February 23, 2024 - import io import sys old_stdout = sys.stdout sys.stdout = text_stream = io.TextIOWrapper(io.BytesIO(), encoding='utf-8') print("Capturing this text.") sys.stdout.seek(0) print(sys.stdout.read()) sys.stdout = old_stdout ... Capturing this text. Capturing this text. The example redirects sys.stdout to capture printed output in a bytes buffer and then reads it back as text. For concise code, Python’s context manager can be used with BytesIO to temporarily wrap bytes as a text stream and automatically handle the cleanup.
🌐
GitHub
github.com › python › cpython › blob › main › Lib › _pyio.py
cpython/Lib/_pyio.py at main · python/cpython
text = TextIOWrapper(buffer, encoding, errors, newline, line_buffering) result = text · text.mode = mode · return result · except: result.close() raise · · # Define a default pure-Python implementation for open_code() # that does not allow hooks.
Author   python
🌐
MindStick
mindstick.com › forum › 161312 › what-is-the-role-of-io-textiowrapper-in-python-input-handling
What Is the Role of io.TextIOWrapper in Python Input Handling? – MindStick
March 29, 2025 - Python transforms file objects into an io.TextIOWrapper is used upon opening files with the default text mode feature of open(). This transformation allows smooth text data manipulation. The system transcends text format between different coding methods to create cross-program compatibility. During file reading operations, such as the following one: with open("example.txt", "r", encoding="utf-8") as file: content = file.read()
🌐
Python.org
discuss.python.org › python help
Change class from '_io.TextIOWrapper' to 'bytes' - Python Help - Discussions on Python.org
February 5, 2024 - Hello Pythonic minds, I have an text file named “ex23_RawBytes_ConvertedToBytes.txt” These are just text with class ‘_io.TextIOWrapper’ when I checked type in python Any way I can convert them into bytes? The reason I am doing this is that I have all the raw bytes in text but their ...
🌐
Python Morsels
pythonmorsels.com › how-read-text-file
How to read from a text file - Python Morsels
October 4, 2021 - Python has a built-in open function that accepts a filename (in this case we're using this diary980.md file), and it gives us back a file object: >>> f = open("diary980.md") >>> f <_io.TextIOWrapper name='diary980.md' mode='r' encoding='UTF-8'>
Top answer
1 of 1
5

Read about TextIOWrapper class in the io module documentation:

A buffered text stream over a BufferedIOBase binary stream.

Edit: use seek function:

seek(offset[, whence])

Change the stream position to the given byte offset. offset is interpreted relative to the position indicated by whence. The default value for whence is SEEK_SET. Values for whence are:

  • SEEK_SET or 0 – start of the stream (the default); offset should be zero or positive
  • SEEK_CUR or 1 – current stream position; offset may be negative
  • SEEK_END or 2 – end of the stream; offset is usually negative

Return the new absolute position.

New in version 3.1: The SEEK_* constants.

New in version 3.3: Some operating systems could support additional values, like os.SEEK_HOLE or os.SEEK_DATA. The valid values for a file could depend on it being open in text or binary mode.

Try the following commented code snippet:

import io, os
output  = io.BytesIO()
wrapper = io.TextIOWrapper(
 output,
 encoding='cp1252',
 # errors=None,         #  default
 # newline=None,        #  default
 line_buffering=True,
 # write_through=False  #  default
 )

wrapper.write('Text1\n')
wrapper.write('Text2\n')
wrapper.write('Text3\n')
# wrapper.flush()                #  If line_buffering is True, flush() is implied
                                 ## when a call to write contains a newline character.

wrapper.seek(0,0)                #  start of the stream
for line in wrapper.readlines():
    print(line)

The rest of my original answer:

print(output.getvalue())         # for debugging purposes

print( wrapper.write('Text4\n')) #  for debugging purposes

# for line in wrapper.read():
for line in output.getvalue().decode('cp1252').split(os.linesep):
    print(line)

Output:

==> D:\test\Python\q44702487.py
b'Text1\r\nText2\r\nText3\r\n'
6
Text1
Text2
Text3
Text4

==>
🌐
Python
docs.python.org › 3.10 › library › io.html
io — Core tools for working with streams — Python 3.10.20 documentation
The TextIOBase ABC extends IOBase. It deals with streams whose bytes represent text, and handles encoding and decoding to and from strings. TextIOWrapper, which extends TextIOBase, is a buffered text interface to a buffered raw stream (BufferedIOBase).