-2

Is there an iterator for reading a file byte by byte?

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. Commented 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. Commented Feb 14, 2016 at 3:08

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.