简体   繁体   中英

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?

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]

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)

Your __init__.py file should look like this:

from file1 import *
from file2 import *

And then you can do:

from subdirectory import *

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM