【问题标题】:'utf8' codec can't decode byte 0xb5 in position 0: invalid start byte'utf8' 编解码器无法解码位置 0 中的字节 0xb5:无效的起始字节
【发布时间】:2017-05-19 04:44:28
【问题描述】:

在将其标记为重复之前,我想明确表示我已经尝试了无数解决方案来消除这种情况,通过使用from __future__ import unicode_literalsstr.encode('utf8')str.decode('utf8') 的每个排列和组合,将@987654324 @ 在文件的开头,什么不是。我知道我做错了,所以我会尽可能具体,我将字典转换为 JSON 数组/对象,并在网页上以原始字符串形式显示它。

我遇到问题的 unicode 字符串是文件名中以“µ”开头的字符串,因此错误发生在以下代码的最后第四行。 files 数组将该字符串索引处的值显示为 \xb5Torrent.lnk

if os.path.isdir(finalDirPath):
        print "is Dir"
        for (path,dir,files) in os.walk(finalDirPath):

            if dir!=[]:
                for i in dir:
                    if not hidden(os.path.join(path,i)):
                        # Here
                        JSONarray.append({"ext":"dir","path":b64(os.path.join(path,i)),"name":i})

            if files!=[]:
                for i in files:
                    if not hidden(os.path.join(path,i)):
                        # Here
                        JSONarray.append({"ext":i.split('.')[-1],"path":b64(os.path.join(path,i)),"name":i})
            break
        jsonStr = {"json":json.dumps(JSONarray)}
        return render(request,"json.html",jsonStr)

这是回溯:

Traceback (most recent call last):
File "C:\Python27\lib\site-packages\django\core\handlers\exception.py", line 39, in inner
response = get_response(request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 249, in _legacy_get_response
response = self._get_response(request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "E:\ICT\Other\Python\Django\trydjango18\src\newsletter\views.py", line 468, in getJSON
JSONarray.append({"ext":i.split('.')[-1],"path":b64(os.path.join(path.encode('utf8'),i)),"name":i})
UnicodeDecodeError: 'utf8' codec can't decode byte 0xb5 in position 0: invalid start byte

【问题讨论】:

  • 可以添加回溯吗?
  • 另外,b64 函数从何而来?你有它的源代码吗?
  • @snakecharmerb 添加,b64函数是base64.b64encode()函数。

标签: python json django python-2.7 unicode


【解决方案1】:

一个更短的例子来说明你的问题:

>>> json.dumps('\xb5Torrent.lnk')

Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    json.dumps('\xb5Torrent.lnk')
  File "C:\Python27\lib\json\__init__.py", line 243, in dumps
    return _default_encoder.encode(obj)
  File "C:\Python27\lib\json\encoder.py", line 201, in encode
    return encode_basestring_ascii(o)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xb5 in position 0: invalid start byte

您的数组 files 包含字节字符串,但 json.dumps() 希望数据中的任何字符串都是 unicode。它假定任何字节字符串都是 utf-8 编码的,但您的字符串使用不同的编码:可能是 latin1 或其他东西。在将它们添加到 JSONarray 结构之前,您需要找出文件系统使用的编码并将所有文件名解码为 un​​icode。

首先检查你的文件系统编码:

import sys
print sys.getfilesystemencoding()

应该告诉您用于文件名的编码,然后您只需确保所有路径操作都使用 unicode:

import sys
fsencoding = sys.getfilesystemencoding()
if os.path.isdir(finalDirPath):
    print "is Dir"
    for (path,dir,files) in os.walk(finalDirPath):
        path = path.decode(fsencoding)
        for i in dir:
            i = i.decode(fsencoding)
            if not hidden(os.path.join(path,i)):
                # Here
                JSONarray.append({
                    "ext": "dir",
                    "path": b64(os.path.join(path,i)),
                    "name": i})
                })

        for i in files:
            i = i.decode(fsencoding)
            if not hidden(os.path.join(path,i)):
                # Here
                JSONarray.append({
                    "ext": i.split('.')[-1],
                    "path": b64(os.path.join(path,i)),
                    "name":i
                })
        break
    jsonStr = {"json":json.dumps(JSONarray)}
    return render(request,"json.html",jsonStr)

【讨论】:

  • 我该如何准确地做到这一点?
  • 成功了!在解码后接收base64字符串时,只需将其编码回代码中的其他位置。将记住此解决方案以备将来使用。谢谢。
猜你喜欢
  • 2020-09-20
  • 1970-01-01
  • 1970-01-01
  • 2014-07-09
  • 2014-04-08
  • 2015-02-23
  • 1970-01-01
  • 2018-06-27
  • 2016-06-27
相关资源
最近更新 更多