0

I have a scenario where i am trying to import the contents in file and use it my script

I have a path : /d/demo in this path i have a abc.py file

This abc.py file contains some pre-defined parameters that i need to use

Taking the filename into a variable : varname Taking the filepath into a variable : varpath

My script :

import sys

varpath='/d/demo'
varname='abc'

sys.path.append(varpath)
from varname import *

This approach is not working : The from varname import * is not replaced with filename like this from abc import *

0x5453
  • 12,753
  • 1
  • 32
  • 61
  • If you want to import based on a runtime value like `varname`, you have to use the built-in [`importlib`](https://docs.python.org/3/library/importlib.html) package. – 0x5453 Aug 16 '21 at 15:49
  • @0x5453 Can you demonstrate with an example –  Aug 16 '21 at 15:50
  • 3
    This thread has some examples: [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) – 0x5453 Aug 16 '21 at 15:51

1 Answers1

0

This should do it

import importlib
import sys

varpath = 'foo'
varname = 'bar'

sys.path.append(varpath)
bar = importlib.import_module(varname)
print(bar.baz)

My directory structure is as follows:

.
├── foo
│   ├── bar.py
│   ├── __init__.py
└── main.py

with bar.py containing:

baz = "Python"
S P Sharan
  • 1,101
  • 9
  • 18