1

I am working in python 3 and I encountered this problem in my code. I wanted to use a variable in a from x import x function inside a loop so that the file being imported from could change without making a bunch of code for each file.

Here is my code:

for x in range(0, 1):

    variable_name = "test"

    from variable_name import *

When I run the code, I get an error: No module named 'variable_name'. I want it to read the variable value as being the filename, not the variable name. Is there a way to fix this?

  • Possible duplicate of [importing a module when the module name is in a variable](https://stackoverflow.com/questions/13598035/importing-a-module-when-the-module-name-is-in-a-variable) – Ashutosh Chapagain Oct 28 '18 at 04:11

1 Answers1

0

Instead of writing from x import x you can try this.

variable_name='test'    
new_module = __import__(variable_name)

The script is equivalent to

import variable_name as new_module