Read .py file variables in another python file using the filepath

Viewed 1773

Considering I have two files - abc.py and xyz.py

abc.py contains the following code -

li = [1, 2, 3, 4]
dt = {'m':1, 'n':4, 'o':9}

I want to read the file abc.py and use the python variables in xyz.py just like how we import using from abc import li, dt.

The path to abc.py (say, path/to/abc.py) will be provided and I want to import the contents and use it in xyz.py just like python variables.

The following code provides the content in a string format, while I can do some coding and get the job done but I want to generalize and look for a better approach to this. Also note, I find using abc.json a better option but due to some reasons I cannot use it for my purpose.

with open(path, "r") as f:
    s = f.read()
    print(s)
1 Answers

First, do not use abc.py as it will clash with another builtin with that name.

What you can do is to add the folder into sys, and then import it.

renaming, for example, to abcfile.py:

import sys
sys.path.insert(1, folder_path)
import abcfile

print(abcfile.li)

>>> [1, 2, 3, 4]

Related