Python中的二进制缓冲区 [英] Binary buffer in Python

查看:555
本文介绍了Python中的二进制缓冲区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,您可以使用 StringIO 获取字符数据的文件缓冲区。 内存映射文件基本上对二进制数据执行类似操作,但它需要一个文件用作基础。 Python是否有一个用于二进制数据的文件对象,并且只是内存,相当于Java的 ByteArrayOutputStream

In Python you can use StringIO for a file-like buffer for character data. Memory-mapped file basically does similar thing for binary data, but it requires a file that is used as the basis. Does Python have a file object that is intended for binary data and is memory only, equivalent to Java's ByteArrayOutputStream?

我的用例是我想在内存中创建一个ZIP文件,并且 ZipFile 需要一个类似文件的对象。

The use-case I have is I want to create a ZIP file in memory, and ZipFile requires a file-like object.

推荐答案

您可能正在寻找 io.BytesIO 课程。它的工作原理与StringIO完全相同,只是它支持二进制数据:

You are probably looking for io.BytesIO class. It works exactly like StringIO except that it supports binary data:

from io import BytesIO
bio = BytesIO(b"some initial binary data: \x00\x01")

StringIO将抛出TypeError:

StringIO will throw TypeError:

from io import StringIO
sio = StringIO(b"some initial binary data: \x00\x01")

这篇关于Python中的二进制缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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