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 to load a file by relative path in python?

My directory structure like below:

./outputsetting.json
./myapp/app.py

I load outputsetting.json file in app.py like below:

with open("..\outputpath.json","r") as f:
    j=json.load(f)

And run in myapp directory it’s ok:

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

python app.py

But if I run app.py in the parent directory:

python .\myapp\app.py 

It raise error

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

How can I load file from disk by the relative directory to the app.py? So I can run it from any place and needn’t modify code every time.
Thanks!

>Solution :

When you start the script from the parent directory, the working directory for the script changes. If you want to access a file that has a specific location relative to the script itself, you can do this:

from pathlib import Path

location = Path(__file__).parent
with open(location / "../outputsetting.json","r") as f:
    j=json.load(f)

Path(__file__) gets the location of the script it is executed in. The .parent thus gives you the folder the script is in, still as a Path object. And you can then navigate to the parent directory from that with location / "../etc"

Or of course in one go:

with open(Path(__file__).parent / "../outputsetting.json","r") as f:
    j=json.load(f)

(Note: your code says outputpath.json, but I assume that’s the same outputsetting.json)

Another solution would be to just change the working directory to be the folder the script is in – but that of course only works if all your scripts and modules are OK with that change:

from pathlib import Path
from os import chdir

chdir(Path(__file__).parent)
with open("../outputsetting.json","r") as f:
    j=json.load(f)

I’d prefer constructing the absolute path as in the previous example though.

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