![](/img/trans.png)
[英]Can't import Python module located on root directory from a different path
[英]Can't import module from different directory python
所以下面是我的文件结构:
/
api.py
app.py
code/
data_api/
weather_data/
get_data_dir/
get_data.py
master_call_dir/
master_call.py
我当前的问题是我正在从app.py
中导入master_call.py
我使用以下代码执行此操作:
-- app.py
import sys
sys.path.append('./code/data_api/weather_data/master_call_dir')
from master_call import master_call_interface as master_call
导入master_call
本身工作得很好,问题是在master_call
内部我导入get_data.py
。 我使用以下代码执行此操作:
-- master_call.py
import sys
sys.path.append("../get_data_dir")
from get_data import get_data_module
打印出sys.path
时,我可以在其中看到../get_data_dir
但 Python 仍然无法在/get_data_dir
中找到get_data.py
文件。
有谁知道如何解决这一问题?
(每个目录中都有一个__init__.py
文件,为了便于阅读,我在这里删除了它)
所以我想通了。 问题是master_call.py
文件的目录是/code/data_api/weather_data/master_call
当前工作目录 (CWD) 是/
因为那是app.py
所在的位置。
要修复它,我们只需在每个 python 脚本中获取绝对文件路径
current_path = os.path.dirname(os.path.realpath(__file__)).replace('\\', '/')
并将其添加到我们附加的任何文件路径中sys.path.append
所以它在实践中看起来像这样:
import sys
import os
current_path = os.path.dirname(os.path.realpath(__file__)).replace('\\', '/')
sys.path.append(f'{current_path}./code/data_api/weather_data/master_call_dir')
from master_call import master_call_interface as master_call
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.