python - 加载多个目录的 Pythonic 方式
问题描述
我有一个目录树如下
定义:
文件夹 A 包含文件夹 B
文件夹 B 包含文件夹 C 和 first.py
文件夹 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"???
解决方案
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
.)
推荐阅读
- javascript - 来自 react-router-dom 的链接无法与 material-ui 正常工作
- python-3.x - 如何使用 Python 请求处理不良代理
- python - Select is not iterable error while select is not iterable error while select a Dropdown option based on user input using Selenium and Python
- parsing - 使用 Parsec 在 Haskell 中编写小型解析器时出现问题
- angular - Angular ErrorHandler 和 HttpErrorResponse
- scala - Azure DataBricks - Deequ - 查找检查失败的行
- python-3.x - QuantReg:“交互式”对象没有“适合”属性
- excel - 将文本从字符串转换为整数
- javascript - 如何将键与对象键数组的总和进行比较?
- python - 无法接收来自另一台服务器的 POST 请求(Flask/Python)