Home > Mobile >  How can I open a json file in modules in python
How can I open a json file in modules in python

Time:04-12

This is my project structure

my project structure

I am opening input.json inside user_input.get_input.py file using the following code:

open('..\\data\\input.json', 'w')

When I run get_input.py file, it works perfectly. But when I run run.py file it shows me this error:

FileNotFoundError: [Errno 2] No such file or directory: '..\\data\\input.json'

I tried using full path too, but no success!

CodePudding user response:

That's because the working directory of the main script you start is the working directory for the ones that you import as well. You can either set the working directory to be user_input in the run configuration in PyCharm, or change the path to data\\input.json when running from run.py.

If you want the relative path independent of working directory in get_input.py, try this:

from pathlib import Path

open(Path(__file__).parent.parent / 'data\\input.json', 'w')

The parent of Path(__file__) is the directory the script itself is in, and its parent is one level up. This would also work:

from pathlib import Path

open(Path(__file__).parent / '..\\data\\input.json', 'w')

If you don't like computing the relative path from various modules, you could also consider giving your application a global root path, accessible from its various modules, which is best depends on the exact application.

  • Related