首页 > 解决方案 > 在python3中访问json文件

问题描述

在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)

标签: jsonpython-3.x

解决方案


您可以做的是使 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,用于在 Python 中打开 JSON 文件


推荐阅读