Does some analog of C# MemoryStream
exist in Python (that could allow me to write binary data from some source direct into memory)? And how would I go about using it?
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.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With