Reading binary file and looping over each byte

前端 未结 12 1322
孤街浪徒
孤街浪徒 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:32

    After trying all the above and using the answer from @Aaron Hall, I was getting memory errors for a ~90 Mb file on a computer running Window 10, 8 Gb RAM and Python 3.5 32-bit. I was recommended by a colleague to use numpy instead and it works wonders.

    By far, the fastest to read an entire binary file (that I have tested) is:

    import numpy as np
    
    file = "binary_file.bin"
    data = np.fromfile(file, 'u1')
    

    Reference

    Multitudes faster than any other methods so far. Hope it helps someone!

提交回复
热议问题