Python中的MemoryStream模拟

ill*_*ant 7 c# python memorystream

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

Ada*_*erg 10

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

该模块实现了一个类文件类,StringIO它读写字符串缓冲区(也称为内存文件).请参阅操作的文件对象的描述(部分文件对象).(对于标准字符串,请参阅strunicode.)...

  • 或者`cStringIO`,它是相同的但是在C中实现了速度. (3认同)

Kei*_*son 5

如果您使用 Python >= 3.0 并尝试了Adam's answer,您会注意到import StringIOimport cStringIO两者都给出了导入错误。这是因为 StringIO现在是io模块的一部分

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!
... 
Run Code Online (Sandbox Code Playgroud)

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