使用Python,我如何像读取文件一样在内存中读取/写入数据? [英] Using Python, how do I to read/write data in memory like I would with a file?

查看:161
本文介绍了使用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.

推荐答案

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆