【问题标题】:How to open python file (file1) using another python file (file2), but the name file2 is the string from the text file?如何使用另一个python文件(file2)打开python文件(file1),但名称file2是文本文件中的字符串?
【发布时间】:2019-06-27 11:29:22
【问题描述】:

我有 python 文件 (file1) 和 (file2) 都在同一个目录中,还有一个文本文件 (ABC.txt) 在第一行包含字符串为“file1”,也保存在同一个目录中。现在我想从file2导入file1,但不像我们通常做的那样(导入file1),而是想通过文本文件字符串打开它。

这是我想做的事情:

#####file2.py####

ABC=open('ABC.txt', 'r')
line= ABC.readlines()

import line[0] ##### the first line of ABC.txt is the file1

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    使用importlib

    import importlib
    
    ABC=open('ABC.txt', 'r')
    line= ABC.readlines()
    
    importlib.import_module(line[0])
    

    【讨论】:

      猜你喜欢
      • 2020-06-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-17
      • 2020-05-23
      • 2022-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多