Importing modules from parent folder

前端 未结 22 2707
梦毁少年i
梦毁少年i 2020-11-21 23:19

I am running Python 2.5.

This is my folder tree:

ptdraft/
  nib.py
  simulations/
    life/
      life.py

(I also have __init

22条回答
  •  暖寄归人
    2020-11-21 23:32

    I had a problem where I had to import a Flask application, that had an import that also needed to import files in separate folders. This is partially using Remi's answer, but suppose we had a repository that looks like this:

    .
    └── service
        └── misc
            └── categories.csv
        └── test
            └── app_test.py
        app.py
        pipeline.py
    

    Then before importing the app object from the app.py file, we change the directory one level up, so when we import the app (which imports the pipeline.py), we can also read in miscellaneous files like a csv file.

    import os,sys,inspect
    currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
    parentdir = os.path.dirname(currentdir)
    sys.path.insert(0,parentdir)
    
    os.chdir('../')
    from app import app
    

    After having imported the Flask app, you can use os.chdir('./test') so that your working directory is not changed.

提交回复
热议问题