首页 > 解决方案 > 加载多个目录的 Pythonic 方式

问题描述

我有一个目录树如下

定义:

  1. 文件夹 A 包含文件夹 B

  2. 文件夹 B 包含文件夹 C 和 first.py

  3. 文件夹 C 包含 inner.py

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

    文件夹_A -> 文件夹_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

如果假设我正在“inner.py”中编写代码。如何仅使用单个代码始终加载 Folder_A 位置,然后根据我的喜好从那里选择 folder_{x}?

我当前的代码:

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?

另请注意,在文件夹_A 之前。文件夹 A 中可能有很多文件夹和更深的加载。

例子:

Folder_king -> Folder_G -> folder_A(现在只在这里。)

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"???

标签: python

解决方案


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


推荐阅读