Reputation: 185
I am wondering whether it is possible to import all Python files from a folder or do I need to import each file individually? I set up a project in which there is a folder “website_functions” with 20 Python files. Each of them contains one function (I use Selenium to access different websites and each file corresponds to one website). Not having to import them individually would make it much faster.
Thanks in advance for your answer
Upvotes: 0
Views: 6187
Reputation: 126
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. From the program that you wish to import the files to, you can import them now using 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
def f1():
print("This is f1() from modules/f.py.")
def f2():
print("This is f2() from modules/f.py.")
modules/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
__all__ = ["f", "g"]
The output of main.py is as follows.
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. For example:
(I've deleted f.py from this example so as to not interfere with the f
attribute of modules
.)
modules/__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.
This is g1() from modules/g.py.
This is g2() from modules/g.py.
Upvotes: 2
Reputation: 638
I would say it's a very bad idea and it violates pep8 styling guide
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)
Upvotes: 0