Reading binary file and looping over each byte

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

    To sum up all the brilliant points of chrispy, Skurmedel, Ben Hoyt and Peter Hansen, this would be the optimal solution for processing a binary file one byte at a time:

    with open("myfile", "rb") as f:
        while True:
            byte = f.read(1)
            if not byte:
                break
            do_stuff_with(ord(byte))
    

    For python versions 2.6 and above, because:

    • python buffers internally - no need to read chunks
    • DRY principle - do not repeat the read line
    • with statement ensures a clean file close
    • 'byte' evaluates to false when there are no more bytes (not when a byte is zero)

    Or use J. F. Sebastians solution for improved speed

    from functools import partial
    
    with open(filename, 'rb') as file:
        for byte in iter(partial(file.read, 1), b''):
            # Do stuff with byte
    

    Or if you want it as a generator function like demonstrated by codeape:

    def bytes_from_file(filename):
        with open(filename, "rb") as f:
            while True:
                byte = f.read(1)
                if not byte:
                    break
                yield(ord(byte))
    
    # example:
    for b in bytes_from_file('filename'):
        do_stuff_with(b)
    

提交回复
热议问题