python导入导入父孙子目录时失败
我有以下目录结构:
C:\project\
| __init__.py
│
└───folder1
| | __init__.py
│ │
│ └───subfolder1
| | __init__.py
│ │ moduleA.py
│ │ moduleB.py
│
└───folder2
| __init__.py
└───subfolder2
| __init__.py
│ myScript.py
在myScript.py文件中,我想从modulea.py导入类。我可以通过以下方式成功从模块中导入类:
import sys
import os
sys.path.append('C:/project/folder1')
from subfolder1.moduleA import ClassA
但是,当我尝试使用以下内容导入时,我会获得“ no Module no Module”:
import sys
import os
sys.path.append('C:/project')
from folder1.subfolder1.moduleA import ClassA
我已经检查了项目/目录中的所有文件的权限,并确保确保所有__ init __。py
文件都是空的(我复制了__ INT __。不确定为什么事情不能正确导入。当前的工作目录(
print(OS.GetCWD())
)指示c:/project/project/folder2/subfolder2
。
这是在Windows 10机器上使用Python 2.7。
I have the following directory structure:
C:\project\
| __init__.py
│
└───folder1
| | __init__.py
│ │
│ └───subfolder1
| | __init__.py
│ │ moduleA.py
│ │ moduleB.py
│
└───folder2
| __init__.py
└───subfolder2
| __init__.py
│ myScript.py
In the myScript.py file I want to import classes from moduleA.py. I can successfully import classes from moduleA in the following manner:
import sys
import os
sys.path.append('C:/project/folder1')
from subfolder1.moduleA import ClassA
However when I attempt to import using the following I get an ImportError "No module named moduleA":
import sys
import os
sys.path.append('C:/project')
from folder1.subfolder1.moduleA import ClassA
I've checked permissions on all files in the project/ directory as well as made sure all __init__.py
files are empty (I copied the __init__.py
from subfolder1 to all other __init__.py
locations) and at this point I'm not sure why things are not importing correctly. Current working directory ( verified by print(os.getcwd())
) indicates C:/project/folder2/subfolder2
.
This is using Python 2.7 on a Windows 10 machine.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
更新:我通过插入SYS.Path的路径而不是附加方法来解决问题。不知道为什么Python最初找不到模块,但这修复了:
sys.path.insert(0,'c:/project')
,而不是
sys.path.append(' c:/project')
Update: I fixed the issue by inserting my path at the begninning of sys.path rather than appending it. No idea why Python couldn't find the module originally but this fixed it:
sys.path.insert(0, 'C:/project')
instead of
sys.path.append('C:/project')