在python3中访问json文件

时间:2019-01-02 09:43:53

标签: json python-3.x

在python3中无法访问

json文件

file=open("D:/arun/textmining/r files/stream_twitter/KCRKTR.json","r",encoding="utf-8")
kcr=json.load(file)
file.close()

这里文件必须可以访问,但是

发生如下错误。

---------------------------------------------------------------------------
JSONDecodeError                           Traceback (most recent call last)
<ipython-input-8-a6e5aade023e> in <module>()
      1 file=open("D:/arun/textmining/r files/stream_twitter/KCRKTR.json","r",encoding="utf-8")
----> 2 kcr=json.load(file)
      3 file.close()

~\Anaconda3\lib\json\__init__.py in load(fp, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
    297         cls=cls, object_hook=object_hook,
    298         parse_float=parse_float, parse_int=parse_int,
--> 299         parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
    300 
    301 

~\Anaconda3\lib\json\__init__.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
    352             parse_int is None and parse_float is None and
    353             parse_constant is None and object_pairs_hook is None and not kw):
--> 354         return _default_decoder.decode(s)
    355     if cls is None:
    356         cls = JSONDecoder

~\Anaconda3\lib\json\decoder.py in decode(self, s, _w)

1 个答案:

答案 0 :(得分:0)

您可以做的是使JSON文件的路径与操作系统无关:

import os
import json
import pprint

PATH = os.path.join('D:'+ os.sep + 'arun' + os.sep + 'textmining' + os.sep
      + 'r files' + os.sep + 'stream _twitter'

file_name = '\\KCRKTR.json' # assuming you are using Windows
# file_name = '/KCRKTR.json' # assuming you are using Linux

with open(PATH+file_name) as json_file:
    kcr = json.load(json_file)

pprint.pprint(kcr) # will pretty print your JSON file

作为参考,这里是SE Query for opening JSON Files in Python