Reading binary file and looping over each byte

前端 未结 12 1104
孤街浪徒
孤街浪徒 2020-11-22 00:53

In Python, how do I read in a binary file and loop over each byte of that file?

12条回答
  •  梦谈多话
    2020-11-22 01:28

    Here's an example of reading Network endian data using Numpy fromfile addressing @Nirmal comments above:

    dtheader= np.dtype([('Start Name','b', (4,)),
                    ('Message Type', np.int32, (1,)),
                    ('Instance', np.int32, (1,)),
                    ('NumItems', np.int32, (1,)),
                    ('Length', np.int32, (1,)),
                    ('ComplexArray', np.int32, (1,))])
    dtheader=dtheader.newbyteorder('>')
    
    headerinfo = np.fromfile(iqfile, dtype=dtheader, count=1)
    
    print(raw['Start Name'])
    

    I hope this helps. The problem is that fromfile doesn't recognize and EOF and allow gracefully breaking out of the loop for files of arbitrary size.

提交回复
热议问题