This is turning out to be trickier than I expected. I have a byte string:
data = b'abcdefghijklmnopqrstuvwxyz'
I want to read this data in chunks of n bytes. Under Python 2, this is trivial using a minor modification to the grouper recipe from the itertools documentation:
def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
args = [iter(iterable)] * n
return (''.join(x) for x in izip_longest(fillvalue=fillvalue, *args))
With this in place, I can call:
>>> list(grouper(data, 2))
And get:
['ab', 'cd', 'ef', 'gh', 'ij', 'kl', 'mn', 'op', 'qr', 'st', 'uv', 'wx', 'yz']
Under Python 3, this gets trickier. The grouper function as written
simply falls over:
>>> list(grouper(data, 2))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in <genexpr>
TypeError: sequence item 0: expected str instance, int found
And this is because in Python 3, when you iterate over a bytestring (like b'foo'), you get a list of integers, rather than a list of bytes:
>>> list(b'foo')
[102, 111, 111]
The python 3 bytes function will help out here:
def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
args = [iter(iterable)] * n
return (bytes(x) for x in izip_longest(fillvalue=fillvalue, *args))
Using that, I get what I want:
>>> list(grouper(data, 2))
[b'ab', b'cd', b'ef', b'gh', b'ij', b'kl', b'mn', b'op', b'qr', b'st', b'uv', b'wx', b'yz']
But (of course!) the bytes function under Python 2 does not behave
the same way. It's just an alias for str, so that results in:
>>> list(grouper(data, 2))
["('a', 'b')", "('c', 'd')", "('e', 'f')", "('g', 'h')", "('i', 'j')", "('k', 'l')", "('m', 'n')", "('o', 'p')", "('q', 'r')", "('s', 't')", "('u', 'v')", "('w', 'x')", "('y', 'z')"]
...which is not at all helpful. I ended up writing the following:
def to_bytes(s):
if six.PY3:
return bytes(s)
else:
return ''.encode('utf-8').join(list(s))
def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
args = [iter(iterable)] * n
return (to_bytes(x) for x in izip_longest(fillvalue=fillvalue, *args))
This seems to work, but is this really the way to do it?