[英]Import file from subdirectory into file in another subdirectory
I have a python project a folder structure like this:我有一个 python 项目,文件夹结构如下:
main_directory
main.py
drivers
__init__.py
xyz.py
utils
__init__.py
connect.py
I want to import connect.py
into xyz.py
and here's my code:我想将
connect.py
导入xyz.py
,这是我的代码:
from utils import connect as dc
But I keep getting this error no matter what I do, please help:但是无论我做什么,我都会不断收到此错误,请帮助:
ModuleNotFoundError: No module named 'utils'
Update : People are telling me to set the path or directory, I don't understand why I need to do this only for importing file.更新:人们告诉我设置路径或目录,我不明白为什么我只需要为导入文件这样做。 This is something that should work automatically.
这是应该自动工作的东西。
In your utils folder __init__.py
should be blank.在你的 utils 文件夹中,
__init__.py
应该是空白的。 If this doesn't work, try adding from __future__ import absolute_import
in your xyz.py
file.如果这不起作用,请尝试在
xyz.py
文件中添加from __future__ import absolute_import
。
You could move your utils folder into drivers, making the path to the to-be imported file a subdirectory of your executing file, like:您可以将您的 utils 文件夹移动到驱动程序中,使要导入的文件的路径成为您的执行文件的子目录,例如:
main_directory/drivers/utils/connect.py
Alternatively, you could try或者,您可以尝试
from ..utils import connect as dc
This will move up a directory before import.这将在导入前向上移动一个目录。
Lasty, you could add the directory to Path in your script via最后,您可以通过以下方式将目录添加到脚本中的路径
import sys
sys.path.insert(0,'/path/to/mod_directory')
For this method, see also this question对于此方法,另请参阅此问题
Check your current directory.检查您的当前目录。 It must be main_directory.
它必须是 main_directory。
import os
print("Current working directory is: ", os.getcwd()
if not, you can change using如果没有,您可以更改使用
os.chdir("path/to/main_directory")
also works with relative path也适用于相对路径
os.chdir('..')
I was also facing same problem when you use row python script so i use the following code at the beginning of the file当您使用第 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)
This way it will search the require file at parent directory.这样它将在父目录中搜索需要的文件。
Hope this will work for you also..希望这也对你有用..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.