How to import all files under a folder in Python?
In Python, you can import all files in a folder using the following method:
import os
# 指定文件夹路径
folder_path = 'path/to/folder'
# 遍历文件夹下的所有文件
for file_name in os.listdir(folder_path):
if os.path.isfile(os.path.join(folder_path, file_name)):
# 导入文件
exec(open(os.path.join(folder_path, file_name)).read())
This code will iterate through all files in a specified folder and execute the contents of each file using the exec function, thereby importing variables, functions, etc. defined in the files into the current Python environment. It is important to note that this method carries a certain security risk, as the exec function will execute any content in the file, including code that may cause unsafe or adverse effects. Therefore, caution should be exercised when using this method.