10

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?

Keith Pinson
  • 7,835
  • 7
  • 61
  • 104
illegal-immigrant
  • 8,089
  • 9
  • 51
  • 84

2 Answers2

12

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, see str and unicode.)...

gnat
  • 6,213
  • 108
  • 53
  • 73
Adam Vandenberg
  • 19,991
  • 9
  • 54
  • 56
5

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.

Community
  • 1
  • 1
Keith Pinson
  • 7,835
  • 7
  • 61
  • 104