【问题标题】:Convert bytes to readable strings in Python 3在 Python 3 中将字节转换为可读字符串
【发布时间】:2014-02-04 02:35:02
【问题描述】:

我有一个保存数据的 .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)

但是,应该有办法将其转换为我可以阅读的字符,即字母或数字,以字符串表示。我似乎把事情复杂化了,因为我确信有一个难以捉摸的内置方法。

【问题讨论】:

  • “我能读懂的字符”是指你能看懂的东西,还是你只想要字符?严格来说,打印已经符合要求;你得到字符b、'、x、0等,你可以阅读它们。另一方面,如果你想要“可读”的东西是你可以理解的,那你可能就不走运了。如您所知,此数据是 JPG 或 RAR 存档。

标签: python hex byte bytearray


【解决方案1】:

使用binascii.hexlify:

>>> import binascii
>>> binascii.hexlify(b'\x00t\xdfe@')
b'0074df6540'

【讨论】:

    猜你喜欢
    • 2018-08-06
    • 1970-01-01
    • 1970-01-01
    • 2021-05-14
    • 2018-06-11
    • 2019-01-25
    • 2015-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多