Importing modules from parent folder

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

    Although it is against all rules, I still want to mention this possibility:

    You can first copy the file from the parent directory to the child directory. Next import it and subsequently remove the copied file:

    for example in life.py:

    import os
    import shutil
    
    shutil.copy('../nib.py', '.')
    import nib
    os.remove('nib.py')
    
    # now you can use it just fine:
    nib.foo()
    

    Of course there might arise several problems when nibs tries to import/read other files with relative imports/paths.

提交回复
热议问题