从Python中的二进制文件的阅读和跨preting数据 [英] Reading and interpreting data from a binary file in Python
本文介绍了从Python中的二进制文件的阅读和跨preting数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想通过字节读取文件的字节是否每个字节的最后一位被设置:
i want to read a file byte by byte and check if the last bit of each byte is set:
#!/usr/bin/python
def main():
fh = open('/tmp/test.txt', 'rb')
try:
byte = fh.read(1)
while byte != "":
if (int(byte,16) & 0x01) is 0x01:
print 1
else:
print 0
byte = fh.read(1)
finally:
fh.close
fh.close()
if __name__ == "__main__":
main()
我得到的错误是:
The error I get is:
Traceback (most recent call last):
File "./mini_01.py", line 21, in <module>
main()
File "./mini_01.py", line 10, in main
if (int(byte,16) & 0x01) is 0x01:
ValueError: invalid literal for int() with base 16: '\xaf'
任何人的想法?我没有成功使用结构和binascii模块。 Thx提前!
Anyone an idea? I didn't succeed using the struct and the binascii modules. Thx in advance!
推荐答案
您想要使用 ORD
而不是 INT
:
if (ord(byte) & 0x01) == 0x01:
这篇关于从Python中的二进制文件的阅读和跨preting数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文