René Bello
René Bello

Reputation: 25

os.path moving through directories

i have this structure in my code.

i need to open the file "data.ptk" from "scrip.py", using os.path i'm able to extract the script path.

my_path = os.path.abspath(os.path.dirname(__file__))

But flowing the structure i need to go back 2 directories and then enter the "data" directory to open the file.

The easy way would be to decompose the string my_path with a split("/"), remove the last 2 words and add "data" ... But I do not think it's the right way

The script.py need to be independent of the OS, that is the reason i'm not able to "hard code" the directory where de pkl file is placed

Any suggestions? thanks.

Upvotes: 1

Views: 72

Answers (1)

Travis Griggs
Travis Griggs

Reputation: 22290

To elaborate on my comment more, you can see the documentation for pathlib here: https://docs.python.org/3/library/pathlib.html?highlight=pathlib#module-pathlib. It is a stock part of python3 (not sure about python2). I think the following would work:

from pathlib import Path
scriptPath = Path(__file__).absolute() # the absolute() is not strictly necessary
srcPath = scriptPath.parent
appPath = srcPath.parent
commonDirectory = appPath.parent # this could have been shortened with scriptPath.parent.parent.parent
dataPath = commonDirectory / 'data'
dtkFile = dataPath / 'data.ptk'

Upvotes: 1

Related Questions