Python - import a module from a directory that is not a package

I have a directory structure similar to this ...

dir/ build.py dir2 dir3/ packages.py 

Now build.py requires packages.py - and note that dir2 not a package.

So, what is the best way to get packages.py loaded in build.py (the directory structure cannot be changed)

EDIT

The solution sys.path.append seems good - but there is one thing: I need to rarely use the packages.py file and store sys.path , which includes a directory that is rarely used, but located at the front - is this the best?

EDIT II

I think the best solution is imp .

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

EDIT III

for Python 3.x

Note that imp.load_source and some other function are deprecated . Therefore, you should use imp.load_module today.

 fp, pathname, description = imp.find_module('packages', '/path/to/packages.py') try: mod = imp.load_module('packages', fp, pathname, description) finally: # since we may exit via an exception, close fp explicitly if fp: fp.close() 
+4
source share
1 answer

You can do:

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

Or even better:

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

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

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

Source: https://habr.com/ru/post/1411761/


All Articles