1

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
  • Did you try adding an `__init__.py` in the `Main` folder and import all the submodules? – Paul Rooney Sep 23 '22 at 07:43
  • @Paul Rooney I have not tried. Could you show me how to do with an answer please? I am not using a class. Thank you –  Sep 23 '22 at 08:30
  • Look at some of the answers [here](https://stackoverflow.com/questions/448271/what-is-init-py-for). Also the [docs](https://docs.python.org/3/reference/import.html#submodules) may help. – Paul Rooney Sep 24 '22 at 00:29
  • @Paul Rooney You're kind, thanks, but I'm new to Python. I have read, but understand little of these things. Can you show me how I can use it in an answer relevant to my case? You would really help me a lot. I will be happy to accept your answer as a solution in case you help me. Thank you –  Sep 24 '22 at 03:02

1 Answers1

1

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.

  • Not what I am looking for. I get errors. Your code makes me specify the main folder in "dirname" first, then I would like to import folder 1, folder 2 and folder 2 at the same time, but your code makes me specify the directory to repeat: in my case there are others too 3 subfolders –  Sep 23 '22 at 06:02
  • FOR THE READERS: I still need help. I have not solved with the kind response of the user. Can you help me? Thank you –  Sep 23 '22 at 06:05