Is there an iterator for reading a file byte by byte?
-
You can use file.read(1) to read a single character from a file. If you really need to this can be typecast to a byte.Jacob H– Jacob H2016-02-14 03:04:53 +00:00Commented Feb 14, 2016 at 3:04
-
it's pretty easy to read the file line-by-line, then iterate the characters in the line, though I know that's not exactly what you're asking.Joseph James– Joseph James2016-02-14 03:08:34 +00:00Commented Feb 14, 2016 at 3:08
Add a comment
|
2 Answers
There isn't an iterator for byte by byte but it is easier enough to create a generator to do it:
def bytefile(f):
b = f.read(1)
while b:
yield b
b = f.read(1)
with open('<file>', 'rb') as f:
for b in bytefile(f):
<do something>
But this really isn't very efficient, and it's not clear what you are trying to do.
Comments
You can mmap the file, if you're using *nix or Windows. This should be the most efficient way to iterate over the bytes of a file:
import mmap
with open('user.py', 'rb') as f:
# memory-map the file, size 0 means whole file
mm = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
for b in mm:
print(b)
mm.close()