You misunderstood what \xhh does in Python strings. Using the \x notation in Python strings is just the syntax for creating specific code points.
You can use '\x61' to create a string, or you can use 'a' ; both are just two ways to tell me a character string with a hexadecimal value of 61, for example. ASCII character:
>>> '\x61' 'a' >>> 'a' 'a' >>> 'a' == '\x61' True
The syntax \xhh then is not a value; in the end result there are no characters \ and no x and no 6 and 1 .
You should just write your line:
somestring = 'abcd' with open("test.bin", "wb") as file: file.write(somestring)
There is nothing magical about binary files; the only difference with a file opened in text mode is that the binary will not automatically translate \n newlines to the line separator standard for your platform; for example, when writing to Windows, \n instead produces \r\n .
You certainly do not need to create hexadecimal escape sequences for writing binary data.
In Python 3, strings are Unicode data and cannot simply be written to a file without encoding, but in Python the str type is already encoded. So, in Python 3, you should use:
somestring = 'abcd' with open("test.bin", "wb") as file: file.write(somestring.encode('ascii'))
or you should use a byte string literal; b'abcd' .
source share