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)
4
  • Take a look at stackoverflow.com/questions/67631/… Commented Mar 29, 2021 at 6: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.. Commented Mar 29, 2021 at 6: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. martin-thoma.com/configuration-files-in-python Commented Mar 29, 2021 at 6:22
  • Yes, it might not be the best idea but there is a reason I have to use .py file specifically. Commented Mar 29, 2021 at 6:31

1 Answer 1

4

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]

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.