“utf8”编解码器无法解码位置0中的字节0xb5:起始于无效

2024-10-01 09:24:57 发布

您现在位置:Python中文网/ 问答频道 /正文

在将其标记为重复之前,我想清楚地表明,我已经尝试过无数种解决方案来消除这种情况,方法是使用from __future__ import unicode_literals来处理str.encode('utf8')和{}的每一个细节和组合,在文件的开头加上# -*- coding: utf-8 -*-等等。我知道我做错了什么,所以我会尽可能的具体化,我正在把一个字典转换成一个JSON数组/对象,并在网页上以它的原始字符串形式显示出来。在

我遇到的问题是文件名中以“µ”开头的unicode字符串,因此错误发生在下面代码的最后四行。files数组将该字符串索引处的值显示为\xb5激流.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)

回溯如下:

^{pr2}$

Tags: path字符串injsonforifosdir
1条回答
网友
1楼 · 发布于 2024-10-01 09:24:57

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

>>> 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结构之前,您需要找出文件系统使用的编码,并将所有文件名解码为unicode。在

首先要检查文件系统编码:

^{pr2}$

应该告诉您文件名使用的编码,然后确保所有路径操作都使用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)

相关问题 更多 >