gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 04:26:04 25 4
gpt4 key购买 nike

根据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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com