我有一个保存数据的 .bin 文件,但我不确定是什么格式或编码。我希望能够将数据转换为可读的内容。格式化不是问题,我可以稍后再做。
我的问题是解析文件。我尝试过使用 struct、binascii 和编解码器,但没有这样的运气。
with open(sys.argv[1], 'rb') as f:
data = f.read()
lists = list(data)
# Below returns that each item is class 'bytes' and a number that appears to be <255
# However, if I add type(i) == bytes it spits an error
for i in lists:
print("Type: ", type(data))
print(i, "\n")
# Below returns that the class is 'bytes' and prints like this: b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xdd\x07\x00\x00\x0b\x00\x00\x00\x18\x00\x00\x00\x00\x00\x00\x00\x0e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x08@\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa0=\xa1D\xc0\x00\x00\x00\x00t\xdfe@
# To my knowledge, this looks like hex notation.
print("Data type: ", type(data))
print(data)
但是,应该有某种方法可以将其转换为我可以读取的字符,即以字符串表示的字母或数字。我似乎把事情过于复杂化了,因为我确信有一个难以捉摸的内置方法。
最佳答案
使用binascii.hexlify
:
>>> import binascii
>>> binascii.hexlify(b'\x00t\xdfe@')
b'0074df6540'
关于python - 在 Python 3 中将字节转换为可读字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21541982/