简体   繁体   中英

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

Okay, so this one really bugs me. I want to ask the user what file I should open in Python and from that answer, I should be able to import the file. For example:

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

However, this results in a syntax error, where it says that there is no module 'e'. How do I fix this?

You could use importlib .

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

You can access variables and functions like mymodule.func1() . More information here

If you're trying to open the file to read the contents you're looking for the open command.

Example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM