[英]Import file from subdirectory into file in another subdirectory
我有一个 python 项目,文件夹结构如下:
main_directory
main.py
drivers
__init__.py
xyz.py
utils
__init__.py
connect.py
我想将connect.py
导入xyz.py
,这是我的代码:
from utils import connect as dc
但是无论我做什么,我都会不断收到此错误,请帮助:
ModuleNotFoundError: No module named 'utils'
更新:人们告诉我设置路径或目录,我不明白为什么我只需要为导入文件这样做。 这是应该自动工作的东西。
在你的 utils 文件夹中, __init__.py
应该是空白的。 如果这不起作用,请尝试在xyz.py
文件中添加from __future__ import absolute_import
。
您可以将您的 utils 文件夹移动到驱动程序中,使要导入的文件的路径成为您的执行文件的子目录,例如:
main_directory/drivers/utils/connect.py
或者,您可以尝试
from ..utils import connect as dc
这将在导入前向上移动一个目录。
最后,您可以通过以下方式将目录添加到脚本中的路径
import sys
sys.path.insert(0,'/path/to/mod_directory')
对于此方法,另请参阅此问题
检查您的当前目录。 它必须是 main_directory。
import os
print("Current working directory is: ", os.getcwd()
如果没有,您可以更改使用
os.chdir("path/to/main_directory")
也适用于相对路径
os.chdir('..')
当您使用第 python 行脚本时,我也遇到了同样的问题,所以我在文件开头使用了以下代码
import os
import sys
current_dir = os.path.dirname(os.path.realpath(__file__))
parent_dir = os.path.dirname(current_dir)
sys.path.append(parent_dir)
这样它将在父目录中搜索需要的文件。
希望这也对你有用..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.