简体   繁体   中英

Pythonic way in loading multiple directories

I have a directories tree as below

Definition:

  1. folder A contains folder B

  2. Folder B contains folder C and first.py

  3. Folder C contains inner.py

    folder_A -> folder_B -> 1. first.py 2. Folder_C -> inner.py

    folder_A -> folder_F -> config.ini

    folder_A -> folder_H -> 1. calc.py 2. Folder_I -> total.py

    folder_A
    ├── folder_B
    │   ├── first.py
    │   └── folder_C
    │       └── inner.py
    ├── folder_F
    │   └── config.ini
    └── folder_H
        ├── calc.py
        └── folder_I
            └── total.py

If lets say I am writing code in "inner.py". How can I just use a single code to always load Folder_A position and then from there just choose folder_{x} based on my preference?

My current code:

MAIN_PATH = '../../folder_F'
os.path.join(MAIN_PATH, 'config.ini')
# I do not wish to use the "../" but a more pythonic or advance way. Is there a cleaner way to do so?

Please also aware that before folder_A. There might be many folder and deeper load into folder A.

Example:

Folder_king -> Folder_G -> folder_A(now only here.)

Reason for not trying to use "../" is because my "inner.py" might be stored in a more deeper folder. If example inside 10x folder then it will be "../../../../../../../../../../folder_F/config.ini"???

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 .)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM