【问题标题】:How to import using a path that is a variable in Python如何使用 Python 中的变量路径导入
【发布时间】:2017-10-13 03:04:41
【问题描述】:

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

除了每次都需要找到一种从新路径导入以进入新目录的方法外,我一切正常。

例如:

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 文档,但没有得到任何工作结果。

【问题讨论】:

  • 你试过os.path模块吗?
  • “访问目录数组并运行程序并在其中创建文件”是什么意思?你想达到什么目标?
  • 例如,我想在每个目录中创建一个文本文件。为此,我必须循环遍历我的数组并获取每个目录名称,以便我可以访问它。
  • 您好。一旦有经验的编辑修改了您的帖子,除非您的问题的技术含义已经改变,否则请不要回复它。您已恢复到包含错误和不必要的网站使用说明的版本,因此我将恢复到上一个​​好的版本。如果您有异议,请通过@halfer 联系我,我们可以邀请主持人。谢谢!

标签: python import directory operating-system sys


【解决方案1】:

您可以使用 '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()

【讨论】:

    【解决方案2】:

    我想在每个目录中创建一个文本文件。为此,我必须 循环遍历我的数组并获取每个目录名称,以便我可以访问它。

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

    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
    

    【讨论】:

    • 我知道导入不用于创建新文件。我的程序本身会这样做,但我已经写好了那部分。我只需要从目录中的文件导入模块,然后在其中创建一个新文件。抱歉,我确实不清楚,现在才意识到。
    猜你喜欢
    • 2016-09-30
    • 2017-09-14
    • 2021-02-06
    • 2014-12-05
    • 2022-01-02
    • 1970-01-01
    • 2019-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多