【发布时间】: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