Pythonic way in loading multiple directories

There is nothing wrong with the use of .. in itself. However, if the overall path is a relative paths, then it will be relative to the process’s current working directory rather than the directory where the script is located. You can avoid this problem by using __file__ to obtain the path of the script itself (which could still be a relative path), and working from there.

MAIN_PATH = os.path.join(os.path.dirname(__file__), '../../')
os.path.join(MAIN_PATH, 'folder_F/config.ini')

If you are particularly keen to avoid .. appearing in the output path unnecessarily, then you can call os.path.normpath on a path containing .. elements and it will simplify the path. For example:

MAIN_PATH = os.path.normpath(
    os.path.join(os.path.dirname(__file__), '../../'))

os.path.join(MAIN_PATH, 'folder_F/config.ini')

(Note – the trailing / on MAIN_PATH above is not strictly necessary, although it would make it more forgiving if you later append a subdirectory path using string concatenation instead of of os.path.join.)

Leave a Comment