1

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?

4

2 に答える 2

1

You should really use the __import__ built-in function together with glob:

os.chdir(path)
for file in glob.glob('*.py')
    __import__(file[:-2])
于 2012-10-15T10:40:04.310 に答える
0

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.

于 2012-10-15T10:53:42.260 に答える