简体   繁体   English

Python:读取和打印二进制文件

[英]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. 基本上,我想为每个字节打印一个介于0和127之间的数字。 However, the first print gives me a smiley face symbol, which I know is not within the first 128 entries in ASCII. 但是,第一张印刷品给我一个笑脸符号,我知道它不在ASCII的前128个条目之内。 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. 因此,即使我仅指定读取f.read中的1个字节,似乎我打印的不仅仅是一个字节。

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. 笑脸是Windows代码页850的字符1(白脸)或2(黑脸),因此一切正常。

在此处输入图片说明

If you want to print the number, just use 如果要打印号码,请使用

print ord(byte)

What read(1) returns is a single-character string. read(1)返回的是一个单字符字符串。 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. 因为Python没有单独的字符类型,而ord()可用于单字符字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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