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,我如何像使用文件一样在内存中读取


- 我如何卸载 PyTorch? 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01