Writing one byte to a file in python 3.x

In a previous Python 2 program, I used the following line to write one byte to a binary:

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

But with Python 3, you cannot write strings and characters to a stream without pre-encoding them in bytes (which makes sense for proper support for multi-byte char)

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

+4
source share
2 answers

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

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

128-255, Python 2 str.encode() str.decode() ASCII , .

0-255 :

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

:

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

six library, six.int2byte() ; Python :

self.output.write(six.int2byte(self.StartElementNew))
+3

, Python 2 3, struct:

import struct
self.output.write(struct.pack('B', self.StartElementNew))
0

Source: https://habr.com/ru/post/1626188/


All Articles