简体   繁体   English

使用Python,如何在内存中读取/写入数据,就像使用文件一样?

[英]Using Python, how do I to read/write data in memory like I would with a file?

I'm used to C++, and I build my data handling classes/functions to handle stream objects instead of files. 我已经习惯了C ++,我构建了数据处理类/函数来处理流对象而不是文件。 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

In this case, the code assumes self.file is a file, opened like so: 在这种情况下,代码假定self.file是一个文件,打开如下:

file = open('somefile.data, 'r+b')

How might I use the same code, yet instead do something like this: 我怎么可能使用相同的代码,而是做这样的事情:

file = get_binary_data()

Where get_binary_data() returns a string of binary data. 其中get_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 ,更快)的实例为内存数据提供类似文件的接口。

看一下Python的StringIO模块, 这里的文档 ,这可能就是你所追求的。

看看'StringIO' (读写字符串作为文件)

使用StringIO

I like the timing of the answer. 我喜欢答案的时机。 (except mine) (除了我的)

We can see response time in milliseconds ? 我们可以看到以毫秒为单位的响应时间?

of-course StringIO 当然是StringIO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM