[英]Can I import all Python files from a folder at once?
I am wondering whether it is possible to import all Python files from a folder or do I need to import each file individually?我想知道是否可以从文件夹中导入所有 Python 文件,还是需要单独导入每个文件? I set up a project in which there is a folder “website_functions” with 20 Python files.
我建立了一个项目,其中有一个文件夹“website_functions”,其中包含 20 个 Python 文件。 Each of them contains one function (I use Selenium to access different websites and each file corresponds to one website).
其中每个包含一个function(我使用Selenium访问不同的网站,每个文件对应一个网站)。 Not having to import them individually would make it much faster.
不必单独导入它们会使其更快。
Thanks in advance for your answer提前感谢您的回答
I would say it's a very bad idea and it violates pep8 styling guide我会说这是一个非常糟糕的主意,它违反了 pep8 样式指南
But if you really have to do it you can hack it like this:但如果你真的必须这样做,你可以像这样破解它:
import importlib
from glob import glob
# Get list of *.py files
modules = glob('*.py')
# Get rid of *.py extension
modules = [module[:-3] for module in modules]
for module in modules:
importlib.import_module(module)
Yes, this is possible.是的,这是可能的。 In the folder full of files that you wish to import, specify all the filenames in a list called
__all__
in the __init__.py
file.在包含您要导入的文件的文件夹中,在
__init__.py
文件中名为__all__
的列表中指定所有文件名。 From the program that you wish to import the files to, you can import them now using from directory import *
.从您希望将文件导入到的程序中,您现在可以使用
from directory import *
导入它们。
Consider the following example.考虑以下示例。
Project directory structure:项目目录结构:
.
|-- main.py
`-- modules
|-- __init__.py
|-- f.py
`-- g.py
1 directory, 4 files
main.py主文件
from modules import *
f.f1()
f.f2()
g.g1()
g.g2()
modules/f.py模块/f.py
def f1():
print("This is f1() from modules/f.py.")
def f2():
print("This is f2() from modules/f.py.")
modules/g.py模块/g.py
def g1():
print("This is g1() from modules/g.py.")
def g2():
print("This is g2() from modules/g.py.")
modules/__init__.py模块/__init__.py
__all__ = ["f", "g"]
The output of main.py is as follows. main.py的output如下。
This is f1() from modules/f.py.
This is f2() from modules/f.py.
This is g1() from modules/g.py.
This is g2() from modules/g.py.
If you want the __all__
list in __init__.py
to be generated automatically every time your program is run, you can do so using the os
library.如果您希望每次运行程序时自动生成
__init__.py
中的__all__
列表,您可以使用os
库来实现。 For example:例如:
(I've deleted f.py from this example so as to not interfere with the f
attribute of modules
.) (我已经从这个例子中删除了 f.py 以免干扰
modules
的f
属性。)
modules/__init__.py模块/__init__.py
import os
__all__ = []
dirname = os.path.dirname(os.path.abspath(__file__))
for f in os.listdir(dirname):
if f != "__init__.py" and os.path.isfile("%s/%s" % (dirname, f)) and f[-3:] == ".py":
__all__.append(f[:-3])
main.py主文件
from modules import *
g.g1()
g.g2()
The output of main.py is as follows. main.py的output如下。
This is g1() from modules/g.py.
This is g2() from modules/g.py.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.