Search code examples
pythonpython-3.xpython-modulesys

import a module up two and down one directory in Python package


I wanted to load a module named mymodule in a directory up two, and down one directory in my file system. Elsewhere I have used

import sys
sys.path.append('../mydirectory')
import mymodule # in mydirectory

in order to go up one, then down one directory (in a package) to grab a module, so I expected this to work:

import sys
sys.path.append('../../mydirectory')
import mymodule

However, I get a ModuleNotFoundError: "No module named 'mymodule'". I'm confused because I ran this in a directory down one from the directory where I had the previous (working) program. (I tried adding __init__.py but it didn't help.) Does anyone know why this doesn't work? Any advice?


Solution

  • this is my go-to-method for just that:

    import sys
    from pathlib import Path
    
    HERE = Path(__file__).parent
    
    sys.path.append(str(HERE / '../../mydirectory'))
    

    using __file__ i do not rely on the current working directory as starting point for relative paths - HERE is the directory the current file is in.

    of course you do not have to use the pathlib module.