Reputation:
If I have the Main folder in which there is Folder 1 (with File 1 inside), Folder 2 (with File 2 inside), Folder 3 (with File 3 inside), is there a way to import all folders and their sub-files at the same time?
Main
> Folder 1 >> File 1
> Folder 2 >> File 2
> Folder 3 >> File 3
I just tried import Main
or from Main import *
, but it doesn't work
I don't want to write like this, because I have so many folders (20) and I would stretch the code:
import Main.Folder1
import Main.Folder2
import Main.Folder3
Upvotes: 1
Views: 158
Reputation: 153
You can loop over the root folder where your folder 1, folder 2, and folder 3 are present. Sample code snippet shown below:
import os
dirname = '/root/directory'
folder_list = os.listdir(dirname)
And once you have a list of directories you can loop over the directory and read the files that are of interest. The sample code snippet is shown below:
import glob
modules = glob.glob('<directory_to_loop>/*.py')
The above code will read all the python files available in the directory.
Upvotes: 1