Using Python, how do I to read/write data in memory like I would with a file?(使用 Python,我如何像使用文件一样在内存中读取/写入数据?)
问题描述
我习惯了 C++,我构建了我的数据处理类/函数来处理流对象而不是文件.我想知道如何修改以下代码,以便它可以处理内存中的二进制数据流,而不是文件句柄.
I'm used to C++, and I build my data handling classes/functions to handle stream objects instead of files. I'd like to know how I might modify the following code, so that it can handle a stream of binary data in memory, rather than a file handle.
def get_count(self):
curr = self.file.tell()
self.file.seek(0, 0)
count, = struct.unpack('I', self.file.read(c_uint32_size))
self.file.seek(curr, 0)
return count
在这种情况下,代码假设 self.file
是一个文件,打开方式如下:
In this case, the code assumes self.file
is a file, opened like so:
file = open('somefile.data, 'r+b')
我怎么可能使用相同的代码,却做这样的事情:
How might I use the same code, yet instead do something like this:
file = get_binary_data()
其中 get_binary_data()
返回一串二进制数据.虽然代码没有显示,但我还需要写入流(我认为不值得为此发布代码).
Where get_binary_data()
returns a string of binary data. Although the code doesn't show it, I also need to write to the stream (I didn't think it was worth posting the code for that).
另外,如果可能的话,我希望新代码也能处理文件.
Also, if possible, I'd like the new code to handle files as well.
推荐答案
您可以使用 StringIO.StringIO(或 cStringIO.StringIO,更快)为内存数据提供类似文件的接口.
You can use an instance of StringIO.StringIO (or cStringIO.StringIO, faster) to give a file-like interface to in-memory data.
这篇关于使用 Python,我如何像使用文件一样在内存中读取/写入数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 Python,我如何像使用文件一样在内存中读取


基础教程推荐
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 包装空间模型 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01