Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

importing a module with a user inputted name in python

Here is what I have been trying to use:

filename = str(input("Enter a file name: "))
file = filename.split('.')
file = file[0]
from file import *

However, the interpreter doesn't attempt to look for the variable assigned to file, and looks for a module named 'file' does anyone have a solution to this?

like image 772
Chase Anderson Avatar asked Sep 29 '26 04:09

Chase Anderson


1 Answers

I think that this might work for you:

import importlib
module = importlib.import_module(filename.split('.')[0])

Then you should be able to use module in order to call any of the imported functions.

like image 199
goodvibration Avatar answered Oct 01 '26 19:10

goodvibration



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!