In Python, how do I read in a binary file and loop over each byte of that file?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Python 3, read all of the file at once:
You can iterate whatever you want using
data
variable.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:
For python versions 2.6 and above, because:
Or use J. F. Sebastians solution for improved speed
Or if you want it as a generator function like demonstrated by codeape:
if you are looking for something speedy, here's a method I've been using that's worked for years:
if you want to iterate chars instead of ints, you can simply use
data = file.read()
, which should be a bytes() object in py3.