Question

I am trying to take in a filename from a user and then use execfile() to execute the file. Below is my code:

print "Please enter the name of the file"
filename = raw_input().split(".")[0]
module = __import__(filename)
execfile(module)             <-- this is where I want to execute the file

I understand that execfile() works as follows:

execfile("example.py")

I am unsure on how to do this when the filename is passed as a variable . I am using python 2.7.

Was it helpful?

Solution

Drop the import and exec the filename. You need the .py extension with this method and it will run any if __name__ == '__main__' section:

filename = raw_input("Please enter the name of the file: ")
execfile(filename)

If you just want to import it, you need to strip the '.py' and it will not execute an if __name__ == '__main__' section:

filename = raw_input("Please enter the name of the file: ").split(".")[0]
module = __import__(filename)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top