【问题标题】:Can you pass a variable to the import function of python?您可以将变量传递给python的导入函数吗?
【发布时间】:2021-01-12 13:23:09
【问题描述】:

我通过“with open()”方法创建了一个 python 文件,现在我想导入该文件,但文件名应该是可变的。

filename = "Test"
with open(filename + ".py", "w+") as file:
    file.write("def main():\n\tpass")

现在在脚本的另一行,我想导入名为类似文件名的 python 脚本。但你不能这样做:

import filename

因为 python 会搜索一个名为“filename”的 python 脚本。但在本例中,它应该导入“Test.py”。有什么建议吗?

【问题讨论】:

标签: python function file import


【解决方案1】:

你想要内置的 import 功能

new_module = __import__(modulename)

所以...

filename = "Test"
with open(filename + ".py", "w+") as file:
    file.write("def main():\n\tpass")
new_module = __import__(filename)

访问https://docs.python.org/3/library/functions.html#__import__

【讨论】:

    猜你喜欢
    • 2020-02-02
    • 1970-01-01
    • 2013-01-20
    • 1970-01-01
    • 2015-10-19
    • 2023-03-20
    • 1970-01-01
    • 2013-03-08
    • 2017-09-17
    相关资源
    最近更新 更多