Daniel
Daniel

Reputation: 945

Why does the path to a file in another dir start sometimes with "./" and sometimes with "../"

I have a file structure that looks like this:

-Project
    -trainingData
        - Folder1
        - Folder2
    -python
        - get_files.py
    -train_model.py

If I want to iterate over each folder in my folder trainingData I use the following function:

data = os.listdir(path_data)
for folder in data:
    # Do sth

path_data is "../training_data" in this case. Which makes sense because I need to go one level up and then into the trainingData folder. In cmd I would also type "cd .." and then "cd trainingData"

But why is the path "./training_data" when I call the function in get_files.py from train_model.py. This does not make sense to me. Isn't the relativ path still the same if I would call the function in get_files.py from the file itself?

Upvotes: 1

Views: 74

Answers (3)

Federico Baù
Federico Baù

Reputation: 7715

why is the path "./training_data" when I call the function in get_files.py from train_model.py

Because you are calling the file from train_model.py hence the relative path is changed (relative to the current running file).

In order to check the Absolute Path you can use os.path.abspath or os.path.realpath.


Also the newest Path.resolve:

Make the path absolute, resolving any symlinks. A new path object is returned:

Upvotes: 1

I break things
I break things

Reputation: 326

The relative path is from the __main__ script, in this case train_model.py. If this wasn't the case then every library or script you imported could all have different relative paths and things would get screwy quickly.

Upvotes: 1

KJDII
KJDII

Reputation: 861

Because the path is relative to the python file being executed. in this case. train_model.py

Upvotes: 2

Related Questions