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

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

Can you pass a variable to the import function of python?

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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__


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...