简体   繁体   English

从 python 目录外部打开 json 文件

[英]Open json file from outside of python directory

I am trying to open the JSON file original.json that is outside of my working directory excelTest.py :我正在尝试打开我的工作目录excelTest.py之外的 JSON 文件original.json 目录

  • excelTest.py is in /Documents/Coding projects/pwdemo/pwdemo excelTest.py在 /Documents/Coding projects/pwdemo/pwdemo
  • original.json is in /Documents/Coding projects/pwdemo original.json在 /Documents/Coding projects/pwdemo

So I've tried to do:所以我试着做:

with open("../original.json", 'r') as json_file:
      json_data = json.load(json_file)

but I get the following error: No such file or directory: '../original.json'但我收到以下错误: No such file or directory: '../original.json'

You can pip install from-root and then use the from_root function like this:您可以pip install from-root ,然后使用 from_root function 像这样:

import json

from from_root import from_root

with open(from_root('original.json'), 'r') as json_file:
      json_data = json.load(json_file)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM