1

I am working on my python code in which I cannot figure out how to use a variable named 'x1' in the following line -

'''

import sys

x_1 = 'file_name'
sys.path.insert(0, r'C:\Users\user\Desktop\file2')

from x_1 import main
main()

'''

The place where I want to use the variable is in the place -> from x1 import main

It is giving an error that the module is not found. Please help me insert a variable in the place.

  • 3
    Does this answer your question? [How to import a module given its name as string?](https://stackoverflow.com/questions/301134/how-to-import-a-module-given-its-name-as-string) – Pedro Maia Dec 17 '21 at 12:52

1 Answers1

0

You can use the spec_from_file_location() from the built-in importlib module (introduced in python 3.1):

import importlib.util

spec = importlib.util.spec_from_file_location("x_1", r'C:\Users\user\Desktop\file2\file_name.py')
x_1 = importlib.util.module_from_spec(spec)
spec.loader.exec_module(x_1)
x_1.main()

Red
  • 26,798
  • 7
  • 36
  • 58