Reputation: 23
I am new to Python and have a problem that I don't know how to solve
I need to write a module (directory C:/Python
) that is able to import and execute all .py
files that are located in some other folder (for example C:/Python/Dir
).
I know how to access to directory (sys.path.append('C:\\Python26\\Dir')
) but how do I make a loop that is able to import all .py
files from this folder?
Upvotes: 1
Views: 1789
Reputation: 5083
If you import all the files in a directory by some glob, how could you access these modules contents without a name? Maybe there is a way to get all imported modules even if they're anonymous (see Return a list of imported Python modules used in a script? - not an easy task), but isn't it easier to list them explicitly?
Maybe you can just create some __init__.py
file in your directory and explicitly list imported files there with appropriate module names.
Upvotes: 0
Reputation: 6014
You should really use the __import__
built-in function together with glob
:
os.chdir(path)
for file in glob.glob('*.py')
__import__(file[:-2])
Upvotes: 1