简体   繁体   中英

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.

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM