Convert binary to list (python)

I would like to be able to open the binary file and create a list (array view) with all the characters, for example: "\ x21 \ x23 \ x22 \ x21 \ x22 \ x31" on ["\ x21", "\ x23", "\ x22 "," \ x21 "," \ x22 "," \ x31 "] What would be the best solution to convert it?

Thank!

+3
source share
4 answers

You need to understand that "\ x21" and "!" are two ways of representing the same thing

therefore "\x21\x23\x22\x21\x22\x31"coincides with'!#"!"1'

>>> "\x21\x23\x22\x21\x22\x31"  == '!#"!"1'
True

>>> infile = open('infile.txt', 'rb')
>>> list(infile.read())
['!', '#', '"', '!', '"', '1']
>>> ['!', '#', '"', '!', '"', '1'] == ["\x21","\x23","\x22","\x21","\x22","\x31"]
True

, , , python

+4

, , , ( b open()):

with open('file.bin', 'rb') as f:
   data = f.read()

data , "\x21\x23\x22\x21\x22\x31".

+2

, myfile.txt "abcdef\n"...

>>> fh = open('myfile.txt', 'rb')
>>> list(fh.read())
['a', 'b', 'c', 'd', 'e', 'f', '\n']
+1

" " , ( !) Python array:

res = array.array('c')
with open('binaryfile', 'rb') as f:
    while True:
        try: res.fromfile(f, 1024 * 1024)
        except EOFError: break

( 1024 * 1024), , - ​​ , , .

+1

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


All Articles