通过继承`io.TextIOWrapper`来子类化文件 - 但它的构造函数有什么签名? [英] Subclassing file by subclassing `io.TextIOWrapper` — but what signature does its constructor have?

查看:727
本文介绍了通过继承`io.TextIOWrapper`来子类化文件 - 但它的构造函数有什么签名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在这篇文章后< c> io.TextIOWrapper a>,虽然我的目标不同。从这开始(NB:动机):

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")

但这给出:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-90-343e18b2e32f> in <module>()
----> 1 f = MyTextIOFile("file.csv")

AttributeError: 'str' object has no attribute 'readable'

实际上,它出现 io.TextIOWrapper s构造函数希望传递一个文件对象。通过反复试验,我发现这个文件对象需要以二进制模式打开。但我无法在任何地方找到文档,而且我不想在未记录的行为之上构建(实际上,尝试继续使用它已经导致我在尝试将对象传递给时遇到问题csv.reader )。在Python 3中对文件对象进行子类化的正确和支持方式是什么?

And indeed, it appears io.TextIOWrappers 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?

我正在使用Python 3.5.0。

I'm using Python 3.5.0.

推荐答案

我认为你要找的文件是

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.

这篇关于通过继承`io.TextIOWrapper`来子类化文件 - 但它的构造函数有什么签名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆