0

In python, how do i load a binary file into a buffer then read individual bytes as numbers not strings.?

1
  • I realize my initial question wasn't all that clear and im still missing something. I understand how to print an entire file as shown with HennyH's example below but what if I only want to print byte 5? or I want to print all bytes from 663 to 765? Commented May 2, 2013 at 10:26

1 Answer 1

3
with open('binary.txt',"rb",buffering=-1) as f:
    for line in f:
        for c in line:
            print(c)

With a file like:

"abcde"

Produces

>>> 
97
98
99
100
101

The optional buffering argument is described here:

buffering is an optional integer used to set the buffering policy. Pass 0 to switch buffering off (only allowed in binary mode), 1 to select line buffering (only usable in text mode), and an integer > 1 to indicate the size of a fixed-size chunk buffer. When no buffering argument is given, the default buffering policy works as follows:

•Binary files are buffered in fixed-size chunks; the size of the buffer is chosen using a heuristic trying to determine the underlying device’s “block size” and falling back on DEFAULT_BUFFER_SIZE. On many systems, the buffer will typically be 4096 or 8192 bytes long.

Python io.open

And if you were really keen and planned on manipulating them, you can convert each line into a bytearray

line = bytearray(line)

To answer your comment this demonstrates how to filter out which characters you iterate over:

with open('binary.txt',"rb",buffering=-1) as f:
    for line in f:
        for c in [b for b in line if b in range(663,765)]: #in a certain range
            print(c)
        for c in [b for b in line if b == 5]: #is a certain number
            print(c)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.