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


in previous python 2 program, used following line writing single byte binary file:

self.output.write(chr(self.startelementnew)) 

but since python 3, can't write strings , chars stream without encoding them bytes first (which makes sense proper multibyte char support)

is there such byte(self.startelementnew) now? , if possible, python 2 compatibility?

for values in range 0-127, following line produce right type in python 2 (str) , 3 (bytes):

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

this doesn't work values in range 128-255 because in python 2, str.encode() call includes implicit str.decode() using ascii codec, fail.

for bytes in range 0-255, i'd define separate function:

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

then use when writing single bytes:

self.output.write(as_byte(self.startelementnew)) 

alternatively, use six library, has six.int2byte() function; library python version test provide suitable version of function:

self.output.write(six.int2byte(self.startelementnew)) 

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -