Does some analog of C# MemoryStream
exist in Python (th开发者_如何学运维at could allow me to write binary data from some source direct into memory)? And how would I go about using it?
StringIO is one possibility: http://docs.python.org/library/stringio.html
This module implements a file-like class,
StringIO
, that reads and writes a string buffer (also known as memory files). See the description of file objects for operations (section File Objects). (For standard strings, seestr
andunicode
.)...
If you are using Python >= 3.0 and tried out Adam's answer, you will notice that import StringIO
or import cStringIO
both give an import error. This is because StringIO is now part of the io
module.
Python 3.4.0 (default, Apr 11 2014, 13:05:11)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import StringIO
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named 'StringIO'
>>> # Huh? Maybe this will work...
...
>>> import cStringIO
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named 'cStringIO'
>>> # Whaaaa...?
...
>>> import io
>>> io.StringIO
<class '_io.StringIO'>
>>> # Oh, good!
...
You can use StringIO
just as if it was a regular Python file: write()
, close()
, and all that jazz, with an additional getvalue()
to retrieve the string.
精彩评论