【问题标题】:StringIO replacement that works with bytes instead of strings?使用字节而不是字符串的 StringIO 替换?
【发布时间】:2011-09-22 16:10:18
【问题描述】:

是否有任何替代 python StringIO 类的替代品,可以使用 bytes 而不是字符串?

这可能不是很明显,但是如果您使用 StringIO 处理二进制数据,那么您在 Python 2.7 或更新版本中就不走运了。

【问题讨论】:

  • 不清楚你的问题是什么。请通过显示适用于 2.6 但不适用于 2.7 的代码来证明您所谓的问题。或者看看我的回答。

标签: python unicode python-2.7 stringio


【解决方案1】:

试试io.BytesIO

正如others have 所指出的,您确实可以在2.7 中使用StringIO,但BytesIO 是向前兼容的不错选择。

【讨论】:

    【解决方案2】:

    在 Python 2.6/2.7 中,io 模块旨在用于与 Python 3.X 兼容。来自文档:

    2.6 版中的新功能。

    io 模块提供 Python 流处理的接口。在下面 Python 2.x,这被提议为 替代内置文件 对象,但在 Python 3.x 中它是 访问文件的默认界面和 流。

    注意由于这个模块已经 主要为 Python 3.x 设计,您 必须意识到,所有用途 本文档中的“字节”是指 str 类型(其中 bytes 是别名), “文本”的所有用法均指 Unicode 类型。此外,这两个 类型是不可互换的 io API。

    在 3.X 之前的 Python 版本中,StringIO 模块包含旧版 StringIO,与 io.StringIO 不同,它可以在 Python 2.6 之前的版本中使用:

    >>> import StringIO
    >>> s=StringIO.StringIO()
    >>> s.write('hello')
    >>> s.getvalue()
    'hello'
    >>> import io
    >>> s=io.StringIO()
    >>> s.write('hello')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: string argument expected, got 'str'
    >>> s.write(u'hello')
    5L
    >>> s.getvalue()
    u'hello'
    

    【讨论】:

      【解决方案3】:

      你说:“这可能不是很明显,但是如果你使用 StringIO 来处理二进制数据,那么你在 Python 2.7 或更新版本上就不走运了”。

      不明显,因为它不是真的。

      如果您的代码可以在 2.6 或更早版本上运行,它会继续在 2.7 上运行。未经编辑的屏幕转储(Windows 命令提示符窗口环绕在第 80 列和所有位置):

      C:\Users\John>\python26\python -c"import sys,StringIO;s=StringIO.StringIO();s.wr
      ite('hello\n');print repr(s.getvalue()), sys.version"
      'hello\n' 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)]
      
      C:\Users\John>\python27\python -c"import sys,StringIO;s=StringIO.StringIO();s.wr
      ite('hello\n');print repr(s.getvalue()), sys.version"
      'hello\n' 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)]
      

      如果您需要编写在 2.7 和 3.x 上运行的代码,请使用 io 模块中的 BytesIO 类。

      如果您需要/想要一个支持 2.7、2.6、... 和 3.x 的代码库,您需要更加努力。使用 six 模块应该有助于很多。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-04-18
        • 1970-01-01
        • 2019-05-31
        • 2011-06-11
        • 2019-02-13
        • 1970-01-01
        • 2021-11-23
        相关资源
        最近更新 更多