【问题标题】:TypeError: Non-Hexadecimal digit found when trying to convert from hex to stringTypeError:尝试从十六进制转换为字符串时发现非十六进制数字
【发布时间】:2017-04-25 05:15:56
【问题描述】:

我有一个以十六进制编码的文件,我正在尝试解码该文件,但我不断收到类型错误。我只使用 python 几个星期,所以如果这似乎是一个基本问题,我很抱歉。

文件内容如下:

4647525137454353554e54544b5831375a42524d345742473246563639554e4a36495a3359304f35394843554637564d4d464f32354143574f495a4f4a4a565849373259544f46335a4358494b424e335047545a51534b47465259475956584d44594f473536494553373653455932574b33574431435a314d35545957594d4e57434444344948324d375858544f4c564f31444a45304947394c32375a584f4845535a534f43353859594c55594e4239363759393738313557475859345a474448434e4f5a5744544d696c6c656e69756d323030303a3035303233626566343737386639343461626439346334653364623062326166

这是我运行的代码:

"received_files/documents/cache/OCAGS0WFYO57JVFGUI4Z437.txt".decode("hex")

这是我回来的:

Traceback (most recent call last):
  File "converter.py", line 1, in <module>
    "received_files/documents/cache/OCAGS0WFYO57JVFGUI4Z437.txt".decode("hex")
  File "/usr/lib/python2.7/encodings/hex_codec.py", line 42, in hex_decode
    output = binascii.a2b_hex(input)
TypeError: Non-hexadecimal digit found

【问题讨论】:

  • 您是否仔细检查过所有字符是否为 0-9 和 A-F?我看不到任何无效字符,但肯定有一个。
  • 无法复制,"received_files/documents/cache/OCAGS0WFYO57JVFGUI4Z437.txt".decode("hex") 产生 AttributeError: 'str' object has no attribute 'decode'

标签: python hex decode typeerror


【解决方案1】:

你给它一个文件名而不是那个文件的内容:

"received_files/documents/cache/OCAGS0WFYO57JVFGUI4Z437.txt".decode("hex")

试试这个:

open("received_files/documents/cache/OCAGS0WFYO57JVFGUI4Z437.txt").read().decode("hex")

【讨论】:

  • @wwii 它返回一个包含文件内容的字符串。
  • str 没有 decode 方法。 'ff'.decode("hex") --&gt; AttributeError。即使它返回 bytes 对象,“十六进制”也不是标准编码 - b'ff'.decode("hex") --&gt; LookupError
  • @wwii docs.python.org/2/library/stdtypes.html 在 2.7 中确实如此。它对我有用,在 3 中可能会有所不同。也在这里:stackoverflow.com/questions/9641440/…
  • 从对该 SO 问题的回答中的评论来看,str.decode() 似乎被删除了 3。由于 OP 使用了它,我假设他们使用的是 2。
  • @无需假设,只需阅读以下内容:文件“/usr/lib/python2.7/encodings/hex_codec.py”,第 42 行,在 hex_decode
猜你喜欢
  • 2018-01-31
  • 2017-08-12
  • 2018-01-22
  • 2014-03-19
  • 2021-12-26
  • 1970-01-01
  • 2019-07-27
  • 1970-01-01
相关资源
最近更新 更多