json - 在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)
解决方案
您可以做的是使 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 文件
推荐阅读
- c - 谁能弄清楚为什么我的将句子拆分为单词的程序(在 C 中)不起作用?
- regex - 正则表达式在匹配字符的行中查找第一次出现的字符
- typescript - 如何创建嵌套的 d.ts 文件?
- akka-stream - 如何从服务器端终止 akka websocket 连接?
- php - 当字段更改值时尝试在 FPDF 中进行分页
- apache-flink - 运行许多作业时,主要的 Flink 瓶颈是什么?
- excel - 在excel数据透视表中,如何计算该行中一行项目的百分比?
- javascript - 使用 express-session 登录,但是在设置 req.session 属性时,它们不保存
- ssl - FIPS BouncyCastle 显示的密码比文档说的少
- sql - 在火花中选择新列作为空字符串