python-3.x - 什么时候应该使用 BytesIO .getvalue() 而不是 .getbuffer()?

标签 python-3.x bytesio

根据BytesIO docs :

getbuffer()

Return a readable and writable view over the contents of the buffer without copying them. Also, mutating the view will transparently update the contents of the buffer:

getvalue()

Return bytes containing the entire contents of the buffer.



所以看起来好像getbuffer更复杂。但是如果你不需要一个可写的 View 呢?那么你会简单地使用 getvalue ?有哪些取舍?

最小的例子

在这个例子中,它们似乎做的完全一样:
# Create an example
from io import BytesIO
bytesio_object = BytesIO(b"Hello World!")

# Write the stuff
with open("output.txt", "wb") as f:
    f.write(bytesio_object.getbuffer())

最佳答案

使用 getbuffer() 更好,因为如果您有非常大的数据,复制它们可能需要很长时间。和(来自 PEP 20):

Explicit is better than implicit.

但是值是未定义的——它可能是 str 或字节。缓冲区总是字节。

关于python-3.x - 什么时候应该使用 BytesIO .getvalue() 而不是 .getbuffer()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61319551/

相关文章:

python - 加载base64图像时出错: PIL. UnidentifiedImageError : cannot identify image file <_io. BytesIO

python - DefaultDict ,在附加元素上,维护按添加顺序排序的键

python - 使用 'value' 作为主键和 'key' 作为辅助键对 python 字典进行排序

macos - 无法安装模块 'docstring'

python - 使用 Pygame 让子弹以一定速度跟随移动物体?

python - BytesIO - 从 s3 下载文件对象但字节流为空

python - 颜色图不随 imshow() 改变

python - 枕头保存到 BytesIO 或 StringIO KeyError : "JPG"

python - 带有 python v2.5 的 BytesIO

python - 将 PIL 图像转换为字节,出现错误