Importing modules from parent folder

前端 未结 22 2731
梦毁少年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:52

    For me the shortest and my favorite oneliner for accessing to the parent directory is:

    sys.path.append(os.path.dirname(os.getcwd()))
    

    or:

    sys.path.insert(1, os.path.dirname(os.getcwd()))
    

    os.getcwd() returns the name of the current working directory, os.path.dirname(directory_name) returns the directory name for the passed one.

    Actually, in my opinion Python project architecture should be done the way where no one module from child directory will use any module from the parent directory. If something like this happens it is worth to rethink about the project tree.

    Another way is to add parent directory to PYTHONPATH system environment variable.

提交回复
热议问题