用字节代替字符串的StringIO替换?

2024-09-27 01:24:58 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有pythonStringIO类的替代品,可以用bytes代替字符串?

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


Tags: 数据字符串版本替代品bytes二进制stringiopythonstringio
3条回答

在Python2.6/2.7中,io模块用于与Python3.X兼容

New in version 2.6.

The io module provides the Python interfaces to stream handling. Under Python 2.x, this is proposed as an alternative to the built-in file object, but in Python 3.x it is the default interface to access files and streams.

Note Since this module has been designed primarily for Python 3.x, you have to be aware that all uses of “bytes” in this document refer to the str type (of which bytes is an alias), and all uses of “text” refer to the unicode type. Furthermore, those two types are not interchangeable in the io APIs.

在3.X之前的Python版本中,StringIO模块包含StringIO的旧版本,与io.StringIO不同,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'

你说:“这可能不太明显,但如果你使用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模块应该会有很大帮助。

试试^{}

正如othershave所指出的,您确实可以在2.7中使用StringIO,但是BytesIO是向前兼容的一个好选择。

相关问题 更多 >

    热门问题