import glob
import importlib
# Locate all .py
files in a specified directory
folder_path = '/path/to/folder'
file_paths = glob.glob(folder_path + '/*.py')
# Dynamically import each file as a module
for file_path in file_paths:
module_name = file_path.split('/')[-1].split('.')[0] # Use the filename as the module name
module = importlib.import_module(module_name)
# At this point, you can access the functions and variables defined in the module
#For example, assume each module contains a function named 'run'
module.run()
```
Note that this approach only imports Python scripts directly in the folder, not files in subdirectories.
If you want to recursively import all .py
files in the directory tree, you can use the os.walk()
function to traverse the entire directory structure.
扫码关注不迷路!!!
郑州升龙商业广场B座25层
service@iqiqiqi.cn
联系电话:187-0363-0315
联系电话:199-3777-5101