0

I want to write a program that uses tkinter.filedialog.askopenfilename to allow the user to select a .py file, and then import that file. I know that when you import a file, the code automatically runs, and that is what I am trying to do. Im am in Python 3 and the answer in How to import a module given its name? does not work for me.

So far, I've tried getting the name of the file chosen and assigning it to a variable and then import it.

from tkinter import filedialog
import os

name = filedialog.askopenfilename(initialdir = "/", title = "Select file", 
filetypes = (("py files", "*.py"), ("all files", "*.*")))
file_to_import = os.path.basename(os.path.splitext(name)[0])
import file_to_import

What I expected to happen is that Python imports whatever I chose, but instead, i get this Error message:

    import file_to_import
ModuleNotFoundError: No module named 'file_to_import'
Jerry Cui
  • 149
  • 7
  • 1
    Possible duplicate of [How to import a module given its name?](https://stackoverflow.com/questions/301134/how-to-import-a-module-given-its-name) – TrebledJ May 29 '19 at 01:42
  • `import file_to_import` will look for a file called "file_to_import" (that's how the interpreter interprets the statement). See the dupe for dynamic importing. – TrebledJ May 29 '19 at 01:43

0 Answers0