2010-11-18 43 views
6

Python中是否存在C#MemoryStream的某些模拟(可以让我将二进制数据从某些源直接写入内存)?我将如何去使用它?Python中的MemoryStream模拟

+0

你问'StringIO'吗? – 2010-11-18 15:34:59

回答

10

StringIO的是一种可能性:http://docs.python.org/library/stringio.html

此模块实现一个类文件的类,StringIO,读取和写入字符串缓冲区中(也称为存储器文件)。请参阅文件对象的操作说明(部分文件对象)。 (对于标准的字符串,见strunicode。)...

+3

或'cStringIO',这是相同的,但在C中以速度实现。 – 2010-11-18 15:47:16

3

如果您正在使用Python> = 3.0,尝试了Adam's answer,你会发现,import StringIOimport cStringIO都给出一个导入错误。这是因为StringIO是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! 
... 

您可以使用StringIO就好像它是一个普通的Python文件:write()close(),和所有爵士乐,另外还有getvalue()检索字符串。