我可以像使用StringIO一样使用cStringIO吗?

时间:2022-04-01 20:26:28

I did this:

我这样做:

import cStringIO.StringIO as StringIO

And I realize I've been using it everywhere. Is that fine? Is it treated the same as StringIO?

我发现我到处都在用它。这是好吗?它和StringIO是一样的吗?

2 个解决方案

#1


25  

They are not the same. cStringIO doesn't correctly handle unicode characters.

他们不一样。cStringIO不能正确地处理unicode字符。

>>> StringIO.StringIO().write(u'\u0080')

>>> cStringIO.StringIO().write(u'\u0080')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\x80' in position 0: ordinal not in range(128)

#2


6  

Nor can you set attributes on a cStringIO.StringIO instance:

也不能在cStringIO上设置属性。StringIO实例:

>>> from cStringIO import StringIO
>>> s = StringIO()
>>> s.name = 'myfile'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'cStringIO.StringO' object has no attribute 'name'

Several libraries depend on File-like objects having either a name or content_type attribute, so cStringIO.StringIO does not work in these instances.

一些库依赖于具有名称或content_type属性的类文件对象,因此cStringIO。StringIO在这些实例中不起作用。

#1


25  

They are not the same. cStringIO doesn't correctly handle unicode characters.

他们不一样。cStringIO不能正确地处理unicode字符。

>>> StringIO.StringIO().write(u'\u0080')

>>> cStringIO.StringIO().write(u'\u0080')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\x80' in position 0: ordinal not in range(128)

#2


6  

Nor can you set attributes on a cStringIO.StringIO instance:

也不能在cStringIO上设置属性。StringIO实例:

>>> from cStringIO import StringIO
>>> s = StringIO()
>>> s.name = 'myfile'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'cStringIO.StringO' object has no attribute 'name'

Several libraries depend on File-like objects having either a name or content_type attribute, so cStringIO.StringIO does not work in these instances.

一些库依赖于具有名称或content_type属性的类文件对象,因此cStringIO。StringIO在这些实例中不起作用。