Search code examples
pythonimport

Importing Python modules from a subdirectory


How can i import my module lib.py in my script module1.py from the following directory structure?

|-
|-lib/lib.py
|-module1/module1.py

Solution

  • This is very, very depend on the use case.

    • For personal usage, I will add the path of the main folder to PYTHONPATH, then import it with: import lib.lib.
    • If lib is an actual package, you can (and should) probably install it and import it the same way.
    • The last case I can think of for now is that if lib and module1 are under the same package already, you can use relative import as well: from ..lib import lib, or something similar.