首页 > 解决方案 > python3.x:从父目录导入文件时出现 ModuleNotFoundError

问题描述

我是 Python 新手。这真的让我很困惑!

我的目录结构是这样的:

Project
   | - subpackage1
           |- a.py
   | - subpackage2
           |- b.py
   | - c.py  

当我导入a.pywithb.pyfrom subpackage1 import a,我得到一个ModuleNotFoundError。好像我无法从父目录导入文件。

一些解决方案建议在每个目录中添加一个空文件__init__.py,但这不起作用。作为一种解决方法,我在每个子文件(即a.pyb.py)中放置了以下内容以访问父目录:

import os
import sys
sys.path.append(os.path.abspath('..'))  

我试图sys.path在子文件中输出,它只包括当前文件路径和anaconda路径,所以我必须追加..sys.path.

我怎么解决这个问题?有没有更有效的方法?

标签: python-3.xpython-import

解决方案


假设我们有这个文件和目录树:

$> tree
.
├── main.py
├── submodule1
│   ├── a.py
│   └── __init__.py
└── submodule2
    ├── b.py
    └── __init__.py

2 directories, 5 files

因此,这是一个如何从a.pyinti进行导入的示例,b.py反之亦然。

一个.py

try:
    # Works when we're at the top lovel and we call main.py
    from submodule1 import b
except ImportError:
    # If we're not in the top level
    # And we're trying to call the file directly
    import sys
    # add the submodules to $PATH
    # sys.path[0] is the current file's path
    sys.path.append(sys.path[0] + '/..')
    from submodule2 import b


def hello_from_a():
    print('hello from a')


if __name__ == '__main__':
    hello_from_a()
    b.hello_from_b()

b.py

try:
    from submodule1 import a
except ImportError:
    import sys
    sys.path.append(sys.path[0] + '/..')
    from submodule1 import a


def hello_from_b():
    print("hello from b")


if __name__ == '__main__':
    hello_from_b()
    a.hello_from_a()

而且,main.py

from submodule1 import a
from submodule2 import b


def main():
    print('hello from main')
    a.hello_from_a()
    b.hello_from_b()


if __name__ == '__main__':
    main()

演示:

当我们在顶层并且我们试图打电话时main.py

$> pwd
/home/user/modules
$> python3 main.py
hello from main
hello from a
hello from b

当我们在 /modules/submodule1 级别并且我们试图调用a.py

$> pwd
/home/user/modules/submodule1
$> python3 a.py
hello from a
hello from b

当我们是 /modules/submodule2 级别并且我们试图调用b.py

$> pwd
/home/user/modules/submodule2
$> python3 b.py
hello from b
hello from a

推荐阅读