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?

1

2 Answers 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])
Sign up to request clarification or add additional context in comments.

1 Comment

sorry, I'm new here, I don't know the rules.I hope now it's ok.
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.

1 Comment

I guess he writes some debug tool or something; you can't really expect from pydoc to create files in protected directories, can you? About the names, he can just make a list and use getattr(globals(), name).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.