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 OverflowHow to access io.TextIOWrapper in python
python 3.x - How can we create a `TextIOWrapper` instance? - Stack Overflow
What Is the Role of io.TextIOWrapper in Python Input Handling?
Change class from '_io.TextIOWrapper' to 'bytes'
Use codecs.getreader to produce a wrapper object:
text_stream = codecs.getreader("utf-8")(bytes_stream)
Works on Python 2 and Python 3.
It turns out you just need to wrap your io.BytesIO in io.BufferedReader which exists on both Python 2 and Python 3.
import io
reader = io.BufferedReader(io.BytesIO("Lorem ipsum".encode("utf-8")))
wrapper = io.TextIOWrapper(reader)
wrapper.read() # returns Lorem ipsum
This answer originally suggested using os.pipe, but the read-side of the pipe would have to be wrapped in io.BufferedReader on Python 2 anyway to work, so this solution is simpler and avoids allocating a pipe.
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}"