Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to import all files from different folder in Python

with __init__.py in the directory, I was able to import it by

from subdirectory.file import *

But I wish to import every file in that subdirectory; so I tried

from subdirectory.* import *

which did not work. Any suggestions?

like image 684
MoneyBall Avatar asked Aug 26 '26 02:08

MoneyBall


2 Answers

Found this method after trying some different solutions (if you have a folder named 'folder' in adjacent dir):

for entry in os.scandir('folder'):
    if entry.is_file():
        string = f'from folder import {entry.name}'[:-3]
        exec (string)
like image 106
ninapberry Avatar answered Aug 28 '26 16:08

ninapberry


If you have the following structure:

$ tree subdirectory/
subdirectory/
├── file1.py
├── file2.py
└── file3.py

and you want a program to automatically pick up every module which is located in this subdirectory and process it in a certain way you could achieve it as follows:

import glob

# Get file paths of all modules.
modules = glob.glob('subdirectory/*.py')

# Dynamically load those modules here.

For how to dynamically load a module see this question.


In your subdirectory/__init__.py you can import all local modules via:

from . import file1
from . import file2
# And so on.

You can import the content of local modules via

from .file1 import *
# And so on.

Then you can import those modules (or the contents) via

from subdirectory import *

With the attribute __all__ in __init__.py you can control what exactly will be imported during a from ... import * statement. So if you don't want file2.py to be imported for example you could do:

__all__ = ['file1', 'file3', ...]

You can access those modules via

import subdirectory
from subdirectory import *

for name in subdirectory.__all__:
    module = locals()[name]
like image 44
a_guest Avatar answered Aug 28 '26 16:08

a_guest



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!