MoneyBall
MoneyBall

Reputation: 2573

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?

Upvotes: 6

Views: 23271

Answers (3)

ninapberry
ninapberry

Reputation: 111

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)

Upvotes: 9

a_guest
a_guest

Reputation: 36309

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]

Upvotes: 7

Ofer Sadan
Ofer Sadan

Reputation: 11942

Your __init__.py file should look like this:

from file1 import *
from file2 import *

And then you can do:

from subdirectory import *

Upvotes: 3

Related Questions