如何使用 Python 中的变量路径导入

How to import using a path that is a variable in Python

我正在尝试制作一个程序,它将遍历并访问一组目录和 运行 一个程序并在其中创建一个文件。

除了我需要想办法每次从新路径导入以到达新目录之外,我一切正常。

例如:

L =["directory1", "directory2", "directory3"]
for i in range(len(L)):
   #I know this is wrong, but just to give an idea
   myPath = "parent."+L[i]
   from myPath import file
   #make file... etc.

显然,当我将 myPath 用作导入路径的变量时,出现错误。我尝试了几种不同的方法,通过 Stack Overflow 在线搜索并阅读 OS 和 Sys 文档,但没有任何效果。

您可以使用 'imp' 模块加载 python 脚本的源代码

import imp
root_dir = '/root/'
dirs =["directory1", "directory2", "directory3"]

for _dir in dirs:
    module_path = os.path.join(root_dir,_dir,'module.py')

    mod = imp.load_source("module_name", module_path)

    # now you can call function in regular way, like mod.some_func()

I want to create a text file inside each directory. To do this I must cycle through my array and take each directory name so I can visit it.

import 用于加载外部模块,而不是创建新文件,如果要创建新文件,请使用 open 语句,并使用 [ 打开尚未存在的文件=13=]模式。注意:目录必须存在

from os.path import join 
L =["directory1", "directory2", "directory3"]
for d in L: # loop through the directories 
    with open(join(d,"filename.txt"), "w") as file:
         pass # or do stuff with the newly created file