8g内存用python读取10文件,使用Python,我如何像读取文件一样在内存中读取/写入数据?...

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

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()

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.

解决方案

You can use an instance of StringIO.StringIO (or cStringIO.StringIO, faster) to give a file-like interface to in-memory data.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值