Reputation: 346
I am writing a piece of Python code, which requires reading a file from a relative position of the script itself.
This is the folder structure:
.
+-- cache
| +-- ..
| +-- population.json
+-- src
| +-- ..
| +-- script.py
+-- ..
I tried something like this:
folder = os.path.dirname(os.path.realpath("__file__"))
path = os.path.join(folder, "..{0}cache{1}population.json".format(os.path.sep, os.path.sep))
with open(path) as f:
population = load(f)
The problem is that folder
is always set to the current folder which I am calling the script from.
So how can I fix it, in order to read the files independently of where I call the script from?
Upvotes: 2
Views: 406
Reputation: 77407
The problem is that you are basing the operation off of the literal string "__file__"
, which python assumes to be the name of a file in the current working directory. You want to use __file__
, the variable holding the name of the script.
Its a bit odd to mix os.path
and hand-crafted paths. But things like os.path.dirname(os.path.dirname(...))
get tedious fast. An alternative is the more compact pathlib
from path lib import Path
path = Path(__file__).absolute().parents[1].joinpath('cache', 'population.json')
But that's just an FYI.
Upvotes: 2