Import a whole folder of python files
<p>I am making a bot in python 3 and wish it to be easily expanded so I have a central file and then one for each command. I wish to know if there is a way to import a sub-directory full of modules without importing each separately. For example:</p>

<pre><code>example
âââ commands
âÂ Â  âââ bar.py
âÂ Â  âââ foo.py
âââ main.py
</code></pre>

<p>And the code in <code>main.py</code>would be something like:</p>

<pre><code>import /commands/*
</code></pre>

<p>Thanks :D</p>

<p><strong>Solution:</strong>
Import each separately with: 
<code>from commands import foo, bar</code></p>

<p><code>from commands import *</code> Does not work.</p>

<p>If you're using python3, the <code>importlib</code> module can be used to dynamically import modules. On python2.x, there is the <code>__import__</code> function but I'm not very familiar with the semantics. As a quick example, </p>

<p>I have 2 files in the current directory</p>

<pre><code># a.py
name = "a"
</code></pre>

<p>and</p>

<pre><code># b.py
name = "b"
</code></pre>

<p>In the same directory, I have this</p>

<pre><code>import glob
import importlib

for f in glob.iglob("*.py"):
    if f.endswith("load.py"):
        continue
    mod_name = f.split(".")[0]
    print ("importing {}".format(mod_name))
    mod = importlib.import_module(mod_name, "")
    print ("Imported {}. Name is {}".format(mod, mod.name))
</code></pre>

<p>This will print</p>

<pre><code>importing b Imported &lt;module 'b' from '/tmp/x/b.py'&gt;. 
Name is b
importing a Imported &lt;module 'a' from '/tmp/x/a.py'&gt;. 
Name is a
</code></pre>

python python-3.x