【问题标题】:How can one import a module from a sibling folder? [duplicate]如何从同级文件夹中导入模块? [复制]
【发布时间】:2020-12-20 21:51:03
【问题描述】:

我的项目结构如下:

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

如何在script.pyscraper.py 中导入helper.py

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

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

有没有更好的方法?
我在 VS Code 上使用 Python 3.9.0 并使用 venv。

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

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

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

    import sys
    sys.path.append('../')
    
    import helpers.helper as helper
    

    【讨论】:

    • 在 helpers 文件夹中尝试使用和不使用 __init__.py,但仍然收到错误 no name 'helper1' in module 'helpers'
    • 您必须拥有__init__.py 并执行from helpers.helper import helper1 或使用上面代码中的导入,您可以在代码中像这样引用它``` helper.helper1`` `.
    猜你喜欢
    • 1970-01-01
    • 2021-07-16
    • 2018-08-08
    • 2020-11-10
    • 2019-02-11
    • 2015-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多