我正在使用Python 3,我需要改回目录以从文件中导入函数。
我尝试做from ..d import function
,但收到错误消息:ValueError: attempted relative import beyond top-level package
。
a
├── b
| └── c.py
├── d.py
基本上,我希望c.py从d.py导入函数。 如果有帮助,我正在使用PyCharm。
答案 0 :(得分:0)
您可以像这样使用sys.path.append(path)
:
import sys
sys.path.append('/my/path/to/a/')
# Now just import what you want from d.py (i.e. if d has MyClass)
from d import MyClass
答案 1 :(得分:0)
尝试为目录创建__init__.py
。
请参阅:https://docs.python.org/2/tutorial/modules.html#packages