sor*_*rin 63 python unicode stringio python-2.7
有没有替代python StringIO类,一个可以使用bytes而不是字符串?
这可能不是很明显,但如果您使用StringIO处理二进制数据,那么您将无法使用Python 2.7或更新版本.
Mar*_*nen 11
在Python 2.6/2.7中,io模块旨在用于与Python 3.X的兼容性.来自文档:
2.6版中的新功能.
io模块为流处理提供了Python接口.在Python 2.x中,这被建议作为内置文件对象的替代,但在Python 3.x中,它是访问文件和流的默认接口.
注意由于此模块主要是为Python 3.x设计的,因此您必须注意本文档中"bytes"的所有用法都是指str类型(其中bytes是别名),以及"text"的所有用法请参阅unicode类型.此外,这两种类型在io API中不可互换.
在早于3.X的Python版本中,StringIO模块包含旧版本的StringIO,与io.StringIO之前2.6版本的Python不同:
>>> 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'
Run Code Online (Sandbox Code Playgroud)
你说:" 这可能不是很明显,但如果你使用StringIO来处理二进制数据,你就不会使用Python 2.7或更新版本 ".
这并不明显,因为它不是真的.
如果您的代码适用于2.6或更早版本,则它将继续在2.7上运行.未编辑的屏幕转储(Windows命令提示符窗口包装在col 80和all):
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)]
Run Code Online (Sandbox Code Playgroud)
如果需要编写在2.7和3.x上运行的代码,请使用模块中的BytesIO类io.
如果您需要/想要一个支持2.7,2.6,...和3.x的单一代码库,您将需要更加努力地工作.使用六个模块应该会有很大帮助.
| 归档时间: |
|
| 查看次数: |
38793 次 |
| 最近记录: |