简体   繁体   English

如何从Python中的不同文件夹导入所有文件

[英]how to import all files from different folder in Python

with __init__.py in the directory, I was able to import it by使用目录中的__init__.py ,我可以通过以下方式导入它

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:并且您希望程序自动选取位于此subdirectory每个模块并以某种方式对其进行处理,您可以按如下方式实现它:

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:在您的subdirectory/__init__.py您可以通过以下方式导入所有本地模块:

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.使用__init__.py __all__属性,您可以控制在from ... import *语句期间将from ... import * So if you don't want file2.py to be imported for example you could do:因此,如果您不想导入file2.py ,例如,您可以执行以下操作:

__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):在尝试了一些不同的解决方案后找到了这个方法(如果相邻目录中有一个名为“folder”的文件夹):

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:您的__init__.py文件应如下所示:

from file1 import *
from file2 import *

And then you can do:然后你可以这样做:

from subdirectory import *

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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