Python How To Import All Files In A Directory

Do you like this?

This code snippet helps you load all the components of a module.


Suppose this is how your project is structured:

In the, if you want to use sub1 and sub2, following are the possible scenarios:
import subfolder.sub1

from subfolder import sub1

import subfolder
If you want to use the following statement:
from subfolder import *
You have 2 options. The first option is as follows:
In /subfolder/, declare:
	import sub1
	import sub2
Another option is below:
In /subfolder/, declare:

import os

for file_ in os.listdir(os.path.dirname(os.path.abspath(__file__))):
    fileext= os.path.splitext(file_)[1].replace(".","").lower()
    filename= os.path.splitext(file_)[0]
    if fileext == "py":
        __import__(filename, globals(), locals())

comments powered by Disqus