在不明确具体路径的情况下,想要从其他相对文件夹导入文件或模块,通常可以使用以下几种方法:
sys.path
修改:
应用于Python,可以在脚本开始时动态添加路径到 sys.path
。__init__.py
文件:
在目录中添加空的 __init__.py
文件,使其成为一个Python包,然后使用相对导入。importlib
或 pkgutil
来动态导入模块。假设我们有以下目录结构:
project/
│
├── main.py
└── subdir/
└── helper.py
main.py 想要导入 helper.py 中的内容。
# main.py
import sys
import os
# 动态添加路径
current_dir = os.path.dirname(os.path.abspath(__file__))
subdir_path = os.path.join(current_dir, 'subdir')
sys.path.append(subdir_path)
# 现在可以导入helper模块
import helper
或者使用相对导入(需要在 subdir
目录下添加 __init__.py
文件):
# 在 subdir/helper.py 中定义一些功能
def greet():
print("Hello from helper!")
# main.py
from subdir import helper
helper.greet()
ModuleNotFoundError
sys.path.append()
或 sys.path.insert()
动态添加路径。__init__.py
文件使目录成为Python包。os.path.normpath()
规范化路径。通过上述方法,可以在不知道确切路径的情况下成功导入其他文件夹中的模块或文件。
领取专属 10元无门槛券
手把手带您无忧上云