Writing an ASCII string as binary in python

I have the string ASCII = "abcdefghijk". I want to write this to a binary file in binary format using python.

I tried the following:

str = "abcdefghijk" fp = file("test.bin", "wb") hexStr = "".join( (("\\x%s") % (x.encode("hex"))) for x in str) fp.write(hexStr) fp.close() 

However, when I open test.bin, I see the following in ascii format instead of binary.

 \x61\x62\x63\x64\x65\x66\x67 

I understand this because there are two abbreviations ("\\ x% s"). How can I solve this problem? Thanks in advance.

Update:

The following is the expected result:

 file = open("test.bin", "wb") file.write("\x61\x62\x63\x64\x65\x66\x67") file.close() 

But how can I achieve this with the string "abcdef" ASCII.

+5
source share
2 answers

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' .

+7
source

I think that you do not necessarily understand what binary / ascii is ... all files are binary in the sense that its just bits. ascii is just a representation of some bits ... 99.9999% of file editors will display your bits as ascii if they can, and if there is no other encoding declared in the file itself ...

 fp.write("abcd") 

exactly equivalent

 fp.write("\x61\x62\x63\x64") 
+1
source

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


All Articles