How to load a file by relative path in python?

Question:

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:

python app.py

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

python .myappapp.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!

Asked By: user2155362

||

Answers:

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.

Answered By: Grismar
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.