Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively import all .py files from all folders [duplicate]

Given one root directory, I need to import all files from all folders (and folders inside other folders) under the root directory.

I figured this could maybe be done with the help of os.walk(), but no idea how to import the files after "walking" through them.

Is there an easy way to do this?

like image 391
Skamah One Avatar asked Jan 14 '15 14:01

Skamah One


People also ask

What is __ all __ in Python?

PACKAGES. In the __init__.py file of a package __all__ is a list of strings with the names of public modules or other objects. Those features are available to wildcard imports. As with modules, __all__ customizes the * when wildcard-importing from the package.

What is the purpose of __ init __ py?

The __init__.py files are required to make Python treat directories containing the file as packages. This prevents directories with a common name, such as string , unintentionally hiding valid modules that occur later on the module search path.

How do I copy multiple files from one directory to another in Python?

copytree() The shutil. copytree() method recursively copies an entire directory tree rooted at source (src) to the destination directory. It is used to recursively copy a file from one location to another.


1 Answers

To import a module by name (in 3.4), use importlib.load_module, which is a "simplifying wrapper around importlib.__import__". You will see the latter mentioned (as a builtin) in other answers. To be useful, you must, of course, assign each module returned to something -- unless you are importing merely to check syntax or generate .pyc files, as in the compile_all module.

like image 167
Terry Jan Reedy Avatar answered Oct 03 '22 13:10

Terry Jan Reedy