-1

i create a python file via the "with open()" method and now i would like to import the file but the filename should be variable.

filename = "Test"
with open(filename + ".py", "w+") as file:
    file.write("def main():\n\tpass")

Now at a other line in the skript i would like to import the python script called like filename. But you cant do something like:

import filename

because then python searches for a python script called "filename". but in this example it should import "Test.py". Any suggestions?

  • Does this answer your question? [How to import a module given its name as string?](https://stackoverflow.com/questions/301134/how-to-import-a-module-given-its-name-as-string) – Mandera Jan 12 '21 at 13:25

1 Answers1

0

You want the built in import function

new_module = __import__(modulename)

so...

filename = "Test"
with open(filename + ".py", "w+") as file:
    file.write("def main():\n\tpass")
new_module = __import__(filename)

Visit https://docs.python.org/3/library/functions.html#__import__