[Python] Cannot import Python modules from sibling directory in Jupyter Notebook running in VS...

Discussão em 'Python' iniciado por Stack, Junho 1, 2025.

  1. Stack

    Stack Membro Participativo

    I am running Jupyter Notebooks inside Visual Studio Code using the official Jupyter extension.

    My project structure is as follows:

    my_project/
    ├── notebooks/
    │ └── analysis.ipynb
    ├── libs/
    │ ├── __init__.py
    │ └── my_module.py


    In analysis.ipynb, I would like to import my_module using either:

    from libs import my_module


    or:

    import my_module


    However, I consistently get the following error:

    ModuleNotFoundError: No module named 'libs'


    I have read the official VS Code Jupyter documentation, but it does not cover anything about import paths or how sys.path is handled.

    Here are the things I have tried:

    1. Changing the working directory:

    import os
    os.chdir("..")


    This does not work. The import still fails.

    1. Manually adding the path to sys.path:

    import sys
    import os
    sys.path.append(os.path.abspath("../libs"))
    import my_module


    This also does not work. The import fails with the same ModuleNotFoundError.

    In a normal Python script (outside of a notebook), these methods usually work for me. But in this case, inside a Jupyter Notebook running in VS Code, they are not working.

    I would like to understand:

    1. Why do these approaches not work in this environment?
    2. How can I properly import modules from sibling or parent directories in this setup?
    3. What is the recommended way to structure this in VS Code when using Jupyter Notebooks?

    Continue reading...

Compartilhe esta Página