pythonexecfile

Using execfile to go to a directory then run a variable


I am making a Python text-assistant. I am trying to use execfile() to run the questions. The file used to ask the question and the command files are in different directories so I cant use import (filename).

My question is how can i run multiple parts, including a variable, in my execfile

This is what I have: execfile ('C:/hidden/assistant/AnsData/', variable, '.py')


Solution

  • If you know where the file to import is, you don't have to resort to execfile hackery. At worst, you can do:

    import importlib
    import sys
    
    sys.path.insert(0, 'C:/hidden/assistant/AnsData/')
    # "variable" is a string naming your module without the .py extension
    answermodule = importlib.import_module(variable)