将变量保存为文件名并从保存的变量名导入函数 - Python

Saving a variable as a file name and importing a function from the saved variable name - Python

好吧,这个真的让我很烦。我想问用户我应该在 Python 中打开什么文件,根据那个答案,我应该能够导入文件。例如:

e = input('File Name?')
from e import *

然而,这会导致语法错误,它表示没有模块 'e'。我该如何解决这个问题?

你可以使用 importlib.

import importlib
file = input('Enter: ')
mymodule = importlib.import_module(file)

您可以像 mymodule.func1() 一样访问变量和函数。 更多信息 here

如果您尝试打开文件以读取内容,您需要使用 open 命令。

示例:

e = input("Enter file: ")
file = open(e)
contents = file.read()