【发布时间】:2017-05-19 04:44:28
【问题描述】:
在将其标记为重复之前,我想明确表示我已经尝试了无数解决方案来消除这种情况,通过使用from __future__ import unicode_literals 对str.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