1

Currently, I have the directory to a file

"../Model.py"

This model has a class called Test.

Using the string of the directory, I want to import and use the class Test.

How do I do so?

(The String will change dynamically)

Ron Arel
  • 371
  • 1
  • 5
  • 14
  • Please provide a minimal reproducible example https://stackoverflow.com/help/minimal-reproducible-example – tim Jul 24 '19 at 21:01
  • Two options: make sure those modules are in a known directory, and add that directory to `sys.path`, then use `importlib.import_module(module_name)` to import the modules dynamically. Or, `importlib.util.spec_from_file_location()` as shown in the other linked post. – Martijn Pieters Jul 25 '19 at 11:24

1 Answers1

-1

From: https://docs.python.org/3/tutorial/modules.html#the-module-search-path

I tested this and I believe it should work for you as well. The code should look as follows:

import sys
directory = '../Model.py'
directory = directory[:-8]
sys.path.append(directory)
from Model import Test
ljagodz
  • 34
  • 8