【问题标题】:Python 0xff bytePython 0xff 字节
【发布时间】:2017-02-22 23:38:33
【问题描述】:

我收到了这个错误:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position: 0, invalid start byte

我找到了这个解决方案:

>>> b"abcde".decode("utf-8")

从这里: Convert bytes to a Python string

但是如果a)你不知道0xff在哪里和/或b)你需要解码一个文件对象,你如何使用它?正确的语法/格式是什么?

我正在解析一个目录,所以我尝试一次浏览一个文件。 (注意:当项目变大时,这将不起作用!!!)

>>> i = "b'0xff'"
>>> with open('firstfile') as f:
...     g=f.readlines()
... 
>>> i in g
False
>>> 0xff in g
False
>>> '0xff' in g
False
>>> b'0xff' in g
False

>>> with open('secondfile') as f:
<snip - same process>

>>> with open('thirdfile') as f:
...     g = f.readlines()
... 
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/usr/local/lib/python3.4/codecs.py", line 313, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

因此,如果这是正确的文件,并且我无法用 Python 打开它(我将它放在崇高的文本中,什么也没找到),我该如何解码或编码呢? 谢谢。

【问题讨论】:

    标签: python file unicode utf-8 byte


    【解决方案1】:
    #how to decode byte 0xff in python
    

    我们知道这是十六进制编码,因此 utf-8 、编解码器和其他解码器无法将此字节解码为字符串。这里我们将使用 'UTF-16' 或 'utf-16' 编码将 0xff 字节数组解码为字符串或 ASCII 字符。

    让我帮助你理解这一点:

    st = "this world is very beautiful"
    print(st.encode('utf-16'))
    >>>b'\xff\xfet\x00h\x00i\x00s\x00 \x00w\x00o\x00r\x00l\x00d\x00 \x00i\x00s\x00 \x00v\x00e\x00r\x00y\x00 \x00b\x00e\x00a\x00u\x00t\x00i\x00f\x00u\x00l\x00'
    

    我们还是想把它转换成简单的 ASCII 字符。 有两种方法可以将 0xff 代码解码为简单字符串。

    st = b'\xff\xfet\x00h\x00i\x00s\x00 \x00w\x00o\x00r\x00l\x00d\x00 \x00i\x00s\x00 \x00v\x00e\x00r\x00y\x00 \x00b\x00e\x00a\x00u\x00t\x00i\x00f\x00u\x00l\x00'  
    

    首先是:

    print(str(st, "utf-16"))
    

    其次是:

    print(st.decode('UTF-16'))   
    

    我们将得到字符串作为输出:

    >>>'this world is very beautiful'
    

    【讨论】:

      【解决方案2】:

      你有很多问题:

      • i = "b'0xff'" 创建一个 7 字节的字符串,而不是单个 0xFF 字节。 i = b'\xff'i = bytes([0xff]) 是正确的方法。

      • open 默认使用local.getpreferredencoding(False) 返回的编码解码文件。以二进制模式打开以获取未解码的原始字节:open('firstfile','rb')

      • g=f.readlines() 返回行列表。 i in g 检查 i 的内容与行列表中一行的内容是否完全匹配

      • 使用有意义的变量名!

      改为:

      byte = b'\xff'
      with open('firstfile','rb') as f:
          file_content = f.read()
      if byte in file_content:
         ...
      

      要解码文件,您需要知道它的正确编码并在打开文件时提供:

      with open('firstfile',encoding='utf8') as f:
          file_content = f.read()
      

      如果你不知道编码,第三者chardet模块可以帮你猜。

      【讨论】:

      【解决方案3】:

      最简单的方法是使用try/except 捕获UnicodeDecodeError,然后您就知道这是您出错的文件。

      该文件很可能不是以 UTF-8 编码的。在这种情况下,您可能希望将文件作为二进制文件读取:

      with open('thirdfile', 'rb') as f:
          g = f.readlines()
      

      如何确定文件的编码是另一个问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-04-10
        • 2019-01-16
        • 2012-05-21
        • 2012-05-28
        • 2018-07-06
        • 1970-01-01
        • 2010-12-13
        • 1970-01-01
        相关资源
        最近更新 更多