I want to know how to read a binary file one by one

Asked 2 years ago, Updated 2 years ago, 134 views

I wonder how to read binary files by 1 byte!

In the file io I've learned so far, the only way to read one line at a time was to read multiple lines at a time

Then is there a way to read one by one like %c on scanf?

file-io python binary

2022-09-21 18:14

1 Answers

Add 'b' to the file mode. 'b' is a mode that means binary mode.

The relevant modes are available in open.

with open("myfile", "rb") as f:
    byte = f.read(1)
    while byte != "":
        # Byte Processing
        byte = f.read(1)

The with statement does not support Python version 2.5 or lower, so you may need to add from__future_import with_statement

You can't read raw characters in Python 3, so you need to change the conditional statements("b"" in "

with open("myfile", "rb") as f:
    byte = f.read(1)
    while byte != b"":
        # # Do stuff with byte.
        byte = f.read(1)

### or

with open("myfile", "rb") as f:
    byte = f.read(1)
    while byte:
        # # Do stuff with byte.
        byte = f.read(1)


2022-09-21 18:14

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.