Is there an iterator for reading a file byte by byte?
Asked
Active
Viewed 1,759 times
-2
-
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 Feb 14 '16 at 03: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 Feb 14 '16 at 03:08
2 Answers
2
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.

AChampion
- 29,683
- 4
- 59
- 75
0
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()

Antti Haapala -- Слава Україні
- 129,958
- 22
- 279
- 321