【问题标题】:How can we create a `TextIOWrapper` instance?我们如何创建一个 `TextIOWrapper` 实例?
【发布时间】:2019-05-31 20:01:34
【问题描述】:

https://docs.python.org/3/library/io.html#overview 说,我们可以通过

创建一个TextIOBase 实例
f = open("myfile.txt", "r", encoding="utf-8")

BufferedIOBase 实例

f = open("myfile.jpg", "rb")

我们如何创建TextIOWrapper 实例?比如可以使用open()来完成吗?

【问题讨论】:

    标签: python-3.x io


    【解决方案1】:

    根据the docs(我的重点):

    open() 函数返回的文件对象类型取决于模式。当 open() 用于以文本模式('w'、'r'、'wt'、'rt' 等)打开文件时,它返回 io.TextIOBase 的子类(特别是 io. TextIOWrapper)。用于以带缓冲的二进制模式打开文件时,返回的类是 io.BufferedIOBase 的子类。

    确实, f = open("myfile.txt", "r", encoding="utf-8") 返回TextIOWrapper

    In [18]: f = open("data", "r", encoding="utf-8")
    
    In [19]: type(f)
    Out[19]: _io.TextIOWrapper
    
    In [20]: type(f).mro()
    Out[20]: [_io.TextIOWrapper, _io._TextIOBase, _io._IOBase, object]
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-18
    • 2012-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多