【发布时间】:2016-11-21 20:53:46
【问题描述】:
我有以下不断更新的数据容器:
data = []
for val, track_id in zip(values,list(track_ids)):
#below
if val < threshold:
#structure data as dictionary
pre_data = {"artist": sp.track(track_id)['artists'][0]['name'], "track":sp.track(track_id)['name'], "feature": filter_name, "value": val}
data.append(pre_data)
#write to file
with open('db/json/' + user + '_' + product + '_' + filter_name + '.json', 'w') as f:
json.dump(data,f, ensure_ascii=False, indent=4, sort_keys=True)
但我遇到了很多这样的错误:
json.dump(data,f, ensure_ascii=False, indent=4, sort_keys=True)
File"/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 190, in dump
fp.write(chunk)
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 6: ordinal not in range(128)
有没有办法一劳永逸地解决这个编码问题?
有人告诉我这样做可以:
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
但是很多人不推荐。
我用python 2.7.10
有什么线索吗?
【问题讨论】:
-
显示完整的错误跟踪,以便我们了解错误的来源。这是 Python 2 还是 3?
-
sys.setdefaultencoding可能在 Python2 中工作,但在 Python3 中不存在。它可以与print()一起使用,但不能与写入文件等其他内容一起使用,因此您必须显示完整的错误消息和导致问题的行。 -
@MarkRansom 已更新,谢谢
-
@furas 上面的完整错误