Python 中是否存在一些 C# 的类似物MemoryStream
(这可以让我将二进制数据从某个源直接写入内存)?我将如何使用它?
问问题
5062 次
2 回答
12
StringIO 是一种可能性:http ://docs.python.org/library/stringio.html
这个模块实现了一个类似文件的类
StringIO
,它读取和写入一个字符串缓冲区(也称为内存文件)。请参阅文件对象的描述以进行操作(文件对象部分)。(对于标准字符串,请参阅str
和unicode
。)...
于 2010-11-18T15:34:49.150 回答
5
如果您使用 Python >= 3.0 并尝试了Adam 的答案,您会注意到import StringIO
或import 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!
...
您可以像使用StringIO
常规 Python 文件一样使用它:write()
、close()
和所有爵士乐,并附加一个getvalue()
来检索字符串。
于 2014-10-25T19:00:53.887 回答