如何从同级文件夹中导入模块?

时间:2020-12-20 21:51:03

标签: python python-3.x

我有以下项目结构:

root
    /scripts
        script.py
    /scrapers
        scraper.py
    /helpers
        helper.py

如何在 helper.pyscript.py 中导入 scraper.py

我让它工作的唯一方法是将所有脚本和抓取工具保存在同一个文件夹中,并将 helpers 文件夹移动到该文件夹​​中,其中包含 __init__.py,如下所示:

root
    /lib
        script.py
        scraper.py
        /helpers
            __init__.py
            helper.py

有没有更好的办法?
我正在使用 Python 3.9.0 和 venv 使用 VS Code。

1 个答案:

答案 0 :(得分:0)

根据this question,您可以执行以下操作:

如果您在任何其他文件中并且想要导入 helper.py,反之亦然。

import sys
sys.path.append('../')

import helpers.helper as helper