How to import a module from a different folder?

后端 未结 2 1132
走了就别回头了
走了就别回头了 2020-12-14 15:52

I have a project which I want to structure like this:

myproject
  __init__.py
  api
    __init__.py
    api.py
  backend
    __init__.py
    backend.py
  mod         


        
2条回答
  •  时光说笑
    2020-12-14 16:19

    Unfortunately, Python will only find your file if your file is in the systems path. But fear not! There is a way around this!

    Using python's sys module, we can add a directory to the path just while Python is running, and once Python stops running, it will remove it from the path.

    You can do this by:

    import sys
    sys.path.insert(0, '/path/to/application/app/folder')
    import [file]
    

    It is important to import sys and set the directory path before you import the file however.

    Good luck!

    Jordan.

提交回复
热议问题