Search code examples
pythonimportdirectory

How to import from another folder (python)


I have a folder structure like:

A/
+-- main.py
+-- bin/
+------ functions.py

I run the code with A as the current working directory.

Within the code of main.py, how do I import the functions.py file?


Solution

  • You need to create an empty file bin/__init__.py. This will tell python that bin is a "package" and should look for modules there.

    from bin import functions
    

    If you want to do something like from bin.functions import * you can add which functions you want to load defining them in __init__.py (more here)

    # __init__.py
    __all__ = ["fun1", "fun2"]
    # doing import * will load those 2
    

    You can find more info here.