Karnivaurus
Karnivaurus

Reputation: 24161

Python: reading and printing a binary file

I have a binary file and I want to read the data, one byte at a time, printing each byte as it runs.

The code I have so far is:

f = open("test.dat", "rb")
try:
    byte = f.read(1)
    while byte != "":
        print byte
        raw_input("Press Enter to continue...")
        byte = f.read(1)
finally:
    f.close()

However, this is not giving me expected results. Basically, I want to print out a number between 0 and 127 for each byte. However, the first print gives me a smiley face symbol, which I know is not within the first 128 entries in ASCII. Therefore, it seems I am printing out more than just a byte - even though I have specified only to read 1 byte in f.read.

What's going on here?

Thanks.

Upvotes: 1

Views: 3994

Answers (2)

Code Painters
Code Painters

Reputation: 7275

What read(1) returns is a single-character string. Try:

print ord(byte[0])

Or as well you can do

print ord(byte)

as Python has no separate character type, and ord() works with single-char strings.

Upvotes: 2

Tim Pietzcker
Tim Pietzcker

Reputation: 336478

The smiley face is Windows codepage-850's character 1 (white face) or 2 (black face), so that's all OK.

enter image description here

If you want to print the number, just use

print ord(byte)

Upvotes: 8

Related Questions