2016-01-28 130 views
4

我想读书,我有使用Python .loads()函数保存在一个文本文件中的JSON文件。我稍后将解析JSON以获取特定的值。json.load()函数给怪“的UnicodeDecodeError:‘ASCII’编解码器不能解码”的错误

我不断收到此错误信息。当我谷歌,没有结果。

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position >85298: ordinal not in range(128)

以下是完整的错误消息:

Traceback (most recent call last): File ".../FirstDegreeKanyeScript.py", >line 10, in data=json.load(data_file) File >"/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/in>it.py", line 265, in load return loads(fp.read(), File >"/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/encodings>/ascii.py", line 26, in decode return codecs.ascii_decode(input, >self.errors)[0] UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 >in position 85298: ordinal not in range(128)

这里是我的代码:

import json 
from pprint import pprint 

with 
open("/Users/.../KanyeAllSongs.txt") as data_file: 
    data=json.load(data_file) 

pprint(data) 

我试过下json.load加入data.decode('utf-8'),但我仍然得到同样的错误。

任何想法可能是什么问题?

+0

您正在使用哪个版本的python?该文件在哪个编码中? – ZetaRift

回答

12

指定在open通话编码。

# encoding is a keyword argument 
open("/Users/.../KanyeAllSongs.txt", encoding='utf-8') as data_file: 
    data=json.load(data_file) 
+2

这工作!谢谢!! – RandyV

+0

@Alik我得到 开放( 'filename.js',编码= 'UTF-8')作为DATA_FILE: ^ 语法错误:无效的语法 –

+0

@FightFireWithFire - 应该很快更新(等待同行评议:HTTP:/ /stackoverflow.com/review/suggested-edits/16132026) – neverendingqs

相关问题