Reputation: 24161
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
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
Reputation: 336478
The smiley face is Windows codepage-850's character 1 (white face) or 2 (black face), so that's all OK.
If you want to print the number, just use
print ord(byte)
Upvotes: 8