from io import BytesIO
buf = BytesIO(); buf<_io.BytesIO at 0x7e185d719350>
Biting through the bytes
Salman Naqvi
Monday, 06 April 2026
![]()
Instantiate a buffer in memory.
Now you can’t directly write data to this buffer.
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[24], line 1 ----> 1 buf.write('This is some data') TypeError: a bytes-like object is required, not 'str'
You need a bytes-like object.
17 bytes have been written to memory, which we can confirm here.
Behind the scenes, the data is stored as binary. However, when printed out, if the byte is a printable character, Python directly renders it out.
We can view the bytes as hexadecimal.
['54',
'68',
'69',
'73',
'20',
'69',
'73',
'20',
'73',
'6f',
'6d',
'65',
'20',
'64',
'61',
'74',
'61']
Or as ASCII encoding.
[84, 104, 105, 115, 32, 105, 115, 32, 115, 111, 109, 101, 32, 100, 97, 116, 97]
Hex escape format.
'\\x54\\x68\\x69\\x73\\x20\\x69\\x73\\x20\\x73\\x6f\\x6d\\x65\\x20\\x64\\x61\\x74\\x61'
Or binary, how it’s actually stored in memory.
'0b10101000b11010000b11010010b11100110b1000000b11010010b11100110b1000000b11100110b11011110b11011010b11001010b1000000b11001000b11000010b11101000b1100001'
Apart from .getvalue(), we can also treat buffer as a list with a pointer, and read the contents being pointed at onward.
An empty string was returned. This is because the pointer is currently at the end of the list. We can seek back to the beginning of the list.
Let’s seek to the fourth byte.
We can see that the fifth byte is indeed blank space.
['T',
'h',
'i',
's',
' ',
'i',
's',
' ',
's',
'o',
'm',
'e',
' ',
'd',
'a',
't',
'a']
If you have any comments, questions, suggestions, feedback, criticisms, or corrections, please do post them down in the comment section below!
Back to top