If we want to get the size of a binary stream (in bytes), we can’t use len() on a BytesIO object.
If we try to use len() on a BytesIO object, we’ll get an exception:
builtins.TypeError: object of type '_io.BytesIO' has no len()
Instead, we need to seek to the end of the stream, and then use the .tell() method to get the ending position of the stream, which will essentially be the size of the stream.
1 2 3 4 5 6 7 8 9101112131415161718
fromioimportBytesIO,SEEK_END# Initialize the word 'Test' in binary form.binary_data=b'Test'# Convert it to a binary streambinary_stream=BytesIO(binary_data)# Go to the end of the stream.binary_stream.seek(0,SEEK_END)# Get the current position, which is now at the end.# We can use this as the size.stream_size=binary_stream.tell()print(stream_size)>>4