Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python write string of bytes to file

How do I write a string of bytes to a file, in byte mode, using python?

I have:

['0x28', '0x0', '0x0', '0x0']

How do I write 0x28, 0x0, 0x0, 0x0 to a file? I don't know how to transform this string to a valid byte and write it.

like image 222
user2483347 Avatar asked Jun 27 '13 17:06

user2483347


People also ask

How do I convert bytes to text files?

First, open a file in binary write mode and then specify the contents to write in the form of bytes. Next, use the write function to write the byte contents to a binary file.

How do I convert a string to a text file in Python?

Python – Write String to Text FileOpen the text file in write mode using open() function. The function returns a file object. Call write() function on the file object, and pass the string to write() function as argument. Once all the writing is done, close the file using close() function.


2 Answers

Map to a bytearray() or bytes() object, then write that to the file:

with open(outputfilename, 'wb') as output:
    output.write(bytearray(int(i, 16) for i in yoursequence))

Another option is to use the binascii.unhexlify() function to turn your hex strings into a bytes value:

from binascii import unhexlify

with open(outputfilename, 'wb') as output:
    output.write(unhexlify(''.join(format(i[2:], '>02s') for i in b)))

Here we have to chop off the 0x part first, then reformat the value to pad it with zeros and join the whole into one string.

like image 84
Martijn Pieters Avatar answered Sep 28 '22 05:09

Martijn Pieters


In Python 3.X, bytes() will turn an integer sequence into a bytes sequence:

>>> bytes([1,65,2,255])
b'\x01A\x02\xff'

A generator expression can be used to convert your sequence into integers (note that int(x,0) converts a string to an integer according to its prefix. 0x selects hex):

>>> list(int(x,0) for x in ['0x28','0x0','0x0','0x0'])
[40, 0, 0, 0]

Combining them:

>>> bytes(int(x,0) for x in ['0x28','0x0','0x0','0x0'])
b'(\x00\x00\x00'

And writing them out:

>>> L = ['0x28','0x0','0x0','0x0']
>>> with open('out.dat','wb') as f:
...  f.write(bytes(int(x,0) for x in L))
...
4
like image 35
Mark Tolonen Avatar answered Sep 28 '22 03:09

Mark Tolonen