According to the 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.
So it seems as if getbuffer
is more complicated. But if you don't need a writable view? Would you then simply use getvalue
? What are the trade-offs?
In this example, it seems as if they do exactly the same:
# 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())
getvalue() just returns the entire contents of the stream regardless of current position.
StringIO and BytesIO are methods that manipulate string and bytes data in memory. StringIO is used for string data and BytesIO is used for binary data. This classes create file like object that operate on string data. The StringIO and BytesIO classes are most useful in scenarios where you need to mimic a normal file.
Using getbuffer() is better, because, if you have really BIG data, copying them may take a long time. And (from PEP 20):
Explicit is better than implicit.But value is undefined - it may be str or bytes. Buffer is always bytes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With