Reading binary file and looping over each byte

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

    If the file is not too big that holding it in memory is a problem:

    with open("filename", "rb") as f:
        bytes_read = f.read()
    for b in bytes_read:
        process_byte(b)
    

    where process_byte represents some operation you want to perform on the passed-in byte.

    If you want to process a chunk at a time:

    with open("filename", "rb") as f:
        bytes_read = f.read(CHUNKSIZE)
        while bytes_read:
            for b in bytes_read:
                process_byte(b)
            bytes_read = f.read(CHUNKSIZE)
    

    The with statement is available in Python 2.5 and greater.

提交回复
热议问题