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?
You should really use the __import__
built-in function together with glob
:
os.chdir(path)
for file in glob.glob('*.py')
__import__(file[:-2])
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.