Reading binary file and looping over each byte

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

    This generator yields bytes from a file, reading the file in chunks:

    def bytes_from_file(filename, chunksize=8192):
        with open(filename, "rb") as f:
            while True:
                chunk = f.read(chunksize)
                if chunk:
                    for b in chunk:
                        yield b
                else:
                    break
    
    # example:
    for b in bytes_from_file('filename'):
        do_stuff_with(b)
    

    See the Python documentation for information on iterators and generators.

提交回复
热议问题