0

I am trying to open JSON file which is located in another directory, and receiving error:

FileNotFoundError: [Errno 2] No such file or directory:

I understand that if I provide relative path, the file has to be in same directory, otherwise the full (root) path has to be provided.

My question is how to avoid it, as at the moment I test it locally, but the code is being used by other people so obviously the path can't be from my root.

Any idea of how to resolve it?

Here is the code:

with open("example.json") as commands:
        commands = json.load(commands)
greybeard
  • 2,249
  • 8
  • 30
  • 66
Gaziox
  • 11
  • 1

1 Answers1

0

You can specify a path relative to your current location.

For example, you're in folder baz and the json file is in folder foo

my
├── bar
│   └── baz           <--- you're here
└── foo
    └── example.json  <--- the file is here

you can access the json file with

with open("../../foo/example.json") as commands:
        commands = json.load(commands)

where .. is the parent of a folder. So ../../foo/example.json is the file two parents up (baz -> bar -> my) and then into the folder foo and finally to the json file example.json.

 

Finally note that if you are on Windows you might need to replace the forward slashes (/) in the path with backward slashes (\).

Gecko
  • 150
  • 9
  • tried exactly same thing, but still receiving error that there is not such file or directory, even if i am sure that the path should be right, and yes, i am using mac, so forward slashes. even if i will place the json file in the folder above, it wont find it – Gaziox Apr 07 '21 at 14:09
  • Maybe try [printing your current path](https://stackoverflow.com/q/3430372)? There might be a chance that you're running of a different directory than you're expecting. – Gecko Apr 07 '21 at 17:31