Reading binary file and looping over each byte

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

    if you are looking for something speedy, here's a method I've been using that's worked for years:

    from array import array
    
    with open( path, 'rb' ) as file:
        data = array( 'B', file.read() ) # buffer the file
    
    # evaluate it's data
    for byte in data:
        v = byte # int value
        c = chr(byte)
    

    if you want to iterate chars instead of ints, you can simply use data = file.read(), which should be a bytes() object in py3.

提交回复
热议问题