简体   繁体   中英

MemoryStream analog in Python

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?

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 .)...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM