问题描述
我习惯了 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,我如何像使用文件一样在内存中读取/写入数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!