3

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)
Amit Pathak
  • 1,145
  • 11
  • 26
  • Take a look at https://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path – Chris Mar 29 '21 at 06:13
  • 1
    how about using json? `{"li": [1, 2, 3, 4], "dt": {'m':1, 'n':4, 'o':9}}`. I don't think it's best idea to use variables from another python file instead you can use json, xml,etc.. – deadshot Mar 29 '21 at 06:15
  • 1
    Is there a reason you are accessing .py files like this for variable content? Is JSON unusable or? Have you considered csv? Have a look at various types of config files that will allow passing of a variable to your python script. https://martin-thoma.com/configuration-files-in-python/ – Jason Chia Mar 29 '21 at 06:22
  • Yes, it might not be the best idea but there is a reason I have to use `.py` file specifically. – Amit Pathak Mar 29 '21 at 06:31

1 Answers1

3

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]