Say that you are on the main_folder
and want to call the file first_file.py
that then opens the file readme.txt
:
main_folder
│
└───first_folder
│ │ first_file.py
│ │
| └───second_folder
│ │ readme.txt
│
└─── ...
Python provides us with an attribute called __file__
that returns the absolute path to the file. For example, say that the content of first_file.py
is just one line that prints this path: print(__file__)
.
Now, if we call first_file.py
from main_folder
we get the same result that if we call it from first_folder
(note that, in Windows, the result is going to be a little bit different):
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
And if we want to obtain the folder of first_file.py
, we import the library os
and we use the method os.path.dirname(__file__)
.
Finally, we just concatenate this folder with the one we want to access from it (second_folder
) and the name of the file (readme.txt
).
Simplifying, the result code is:
import os
DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
And the value of README_PATH:
"/Users/<username>/Documents/github/main_folder/first_folder/second_folder/readme.txt"
This way, you also won't get any problems related to the Visual Studio Code debugger with the path and you'll be able to call the first_file.py
from wherever you want