Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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():
pass")

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.0k views
Welcome To Ask or Share your Answers For Others

1 Answer

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():
pass")
new_module = __import__(filename)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...