如果文件名是可变的,是否可以导入文件?

2024-04-20 01:59:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个变量定义如下:

file = "filename_" + getpass.getuser()

我想导入这个文件

import file

这可能吗?你知道吗


Tags: 文件import定义filenamefilegetpassgetuser
2条回答

有多种方法可以做到这一点,有些方法比其他方法更像Python。 (需要指出的是,动态导入模块有点不常见,通常有一种更好的方法。)

使用exec

module_name = "filename_{0}".format(getpass.getuser())
exec_string = "import {0}".format(module_name)
exec exec_string

这会将模块引入名称空间,但在某种程度上容易受到任意代码执行的攻击,因此需要进行eval调用才能实际访问模块。你知道吗

更好的方法是使用__import__importlib模块,这两个模块在python2.X中可以互换

module = __import__(module_name)

或者

import importlib
module = importlib.import_module(module_name)

看看^{}内置函数。你知道吗

您可能还对^{}^{}模块感兴趣。你知道吗

相关问题 更多 >