how to import all files from different folder in Python

13,251

Solution 1

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]

Solution 2

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)

Solution 3

Your __init__.py file should look like this:

from file1 import *
from file2 import *

And then you can do:

from subdirectory import *
Share:
13,251

Related videos on Youtube

MoneyBall
Author by

MoneyBall

BY DAY: Alt-Rock Ninja Cowgirl at Verifidan Dynamics BY NIGHT: I write code and code rights for penalcoders.example.org, an awesome non-profit that will totally take your money at that link. My kids are cuter than yours. FOR FUN: C++ Jokes, Segway Roller Derby, NYT Sat. Crosswords (in Sharpie!), Ostrich Grooming. "If you see scary things, look for the helpers - you'll always see people helping." -Fred Rogers

Updated on June 21, 2022

Comments

  • MoneyBall
    MoneyBall almost 2 years

    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?