[Python] What is the idiomatic way to iterate over a binary file?

Discussão em 'Python' iniciado por Stack, Março 2, 2025.

  1. Stack

    Stack Membro Participativo

    With a text file, I can write this:

    with open(path, 'r') as file:
    for line in file:
    # handle the line


    This is equivalent to this:

    with open(path, 'r') as file:
    for line in iter(file.readline, ''):
    # handle the line


    This idiom is documented in PEP 234 but I have failed to locate a similar idiom for binary files.

    With a binary file, I can write this:

    with open(path, 'rb') as file:
    while True:
    chunk = file.read(1024 * 64)
    if not chunk:
    break
    # handle the chunk


    I have tried the same idiom that with a text file:

    def make_read(file, size):
    def read():
    return file.read(size)
    return read

    with open(path, 'rb') as file:
    for chunk in iter(make_read(file, 1024 * 64), b''):
    # handle the chunk


    Is it the idiomatic way to iterate over a binary file in Python?

    Continue reading...

Compartilhe esta Página