Python中是否存在C#MemoryStream
的模拟(可以让我将某些源的二进制数据直接写入内存)?我将如何使用它?
答案 0 :(得分:10)
StringIO是一种可能性:http://docs.python.org/library/stringio.html
该模块实现了一个类文件类
StringIO
,它读写字符串缓冲区(也称为内存文件)。请参阅文件对象的操作说明(文件对象部分)。 (有关标准字符串,请参阅str
和unicode
。)...
答案 1 :(得分:3)
如果您使用的是Python> = 3.0并尝试Adam's answer,则会注意到import StringIO
或import 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()
来检索字符串