Open json file from outside of python directory

Viewed 28

I am trying to open the JSON file original.json that is outside of my working directory excelTest.py: Directory

  • excelTest.py is in /Documents/Coding projects/pwdemo/pwdemo
  • original.json is in /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'

1 Answers

You can pip install from-root and then use the from_root function like this:

import json

from from_root import from_root

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