I'm trying to subclass io.TextIOWrapper
following this post, although my aims are different. Starting off with this (NB: motivation):
class MyTextIOFile(io.TextIOWrapper):
def read(self, *args):
cont = super().read(*args)
return cont.replace("\x00", "")
I'm trying to open a file using my constructor using
In [81]: f = MyTextIOFile("file.csv")
but this gives:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-90-343e18b2e32f> in <module>()
----> 1 f = MyTextIOFile("file.csv")
AttributeError: 'str' object has no attribute 'readable'
And indeed, it appears io.TextIOWrapper
s constructor expects to be passed a file object. Through trial and error, I discovered this file object needs to be opened in binary mode. But I can't find documentation anywhere, and I don't feel like building on top of undocumented behaviour (indeed, one attempt to go ahead with it already lead me to problems when trying to pass my object to csv.reader
). What is the correct and supported way to subclass a file object in Python 3?
I'm using Python 3.5.0.
I think the documentation you are looking for is
class io.TextIOWrapper(buffer, encoding=None, errors=None, newline=None, line_buffering=False)
A buffered text stream over a BufferedIOBase binary stream. [...]
The first argument is a binary stream, which implies something opened in binary mode by open
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With