Search code examples
pythonpython-3.xpython-import

What's the best way to import a module from a directory that's not a package?


My directory structure:

dir/
  build.py
dir2
  dir3/
  packages.py

build.py needs packages.py. dir2 is not a package. What's the best way to get packages.py loaded into build.py (the directory structure can't be changed)?

The sys.path.append solution seems good but I need to use the packages.py file rarely and keeping a sys.path that includes a directory used rarely, but is at the front, is that the best thing?


Solution

  • You could do:

    sys.path.append('./dir2/dir3')
    import packages
    

    Or better yet:

    sys.path.append(os.path.join(os.path.dirname(__file__), 'dir2/dir3'))
    import packages
    

    Or (taken from here: How to import a module given the full path?)

    import imp    
    packages = imp.load_source('packages', '/path/to/packages.py')