Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I open a json file in modules in python

This is my project structure

my project structure

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading