Python How To Import All Files In A Directory

Do you like this?

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


Content:

Suppose this is how your project is structured:

/root
	__init__.py
	main.py
	/subfolder
		__init__.py
		sub1.py
		sub2.py
In the main.py, if you want to use sub1 and sub2, following are the possible scenarios:
import subfolder.sub1
sub1.declared_method()

from subfolder import sub1
sub1.declared_method()

import subfolder
subfolder.sub1.declared_method()
If you want to use the following statement:
from subfolder import *
You have 2 options. The first option is as follows:
In /subfolder/__init__.py, declare:
	import sub1
	import sub2
Another option is below:
In /subfolder/__init__.py, 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