StringIO replacement that works with bytes instead of strings?
Is there any replacement for python StringIO
class, one that will work with bytes
instead of strings?
It may not be obvious but if you used StringIO for processing binary data you are out of luck with Python 2.7 or newer.
Solution 1:
Try io.BytesIO
.
As others have pointed out, you can indeed use StringIO
in 2.7, but BytesIO
is a good choice for forward-compatibility.
Solution 2:
In Python 2.6/2.7, the io module is intended to be used for compatibility with Python 3.X. From the docs:
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.
In Python versions earlier than 3.X the StringIO module contains the legacy version of StringIO, which unlike io.StringIO
can be used in pre-2.6 versions of 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'