Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write a single byte to a file in python 3.x

In a previous Python 2 program, I used the following line for writing a single byte to a binary file:

self.output.write(chr(self.StartElementNew))

But since Python 3, you can't write strings and chars to a stream without encoding them to bytes first (which makes sense for proper multibyte char support)

Is there something such as byte(self.StartElementNew) now? And if possible, with Python 2 compatibility?

like image 886
galinette Avatar asked Sep 26 '22 13:09

galinette


1 Answers

For values in the range 0-127, the following line will always produce the right type in Python 2 (str) and 3 (bytes):

chr(self.StartElementNew).encode('ascii')

This doesn't work for values in the range 128-255 because in Python 2, the str.encode() call includes an implicit str.decode() using ASCII as the codec, which will fail.

For bytes in the range 0-255, I'd define a separate function:

if sys.version_info.major >= 3:
    as_byte = lambda value: bytes([value])
else:
    as_byte = chr

then use that when writing single bytes:

self.output.write(as_byte(self.StartElementNew))

Alternatively, use the six library, it has a six.int2byte() function; the library does the Python version test for you to provide you with a suitable version of the function:

self.output.write(six.int2byte(self.StartElementNew))
like image 75
Martijn Pieters Avatar answered Sep 28 '22 05:09

Martijn Pieters