Roger That
Roger That

Reputation: 95

Variable in other python file, how to load in?

I've got a program that runs now but because I want several testcases I moved the dict that it uses to an external file. But now I am unable to read in the data in the same way.

This is what one of the testcases looks like, working when it is in the same file.

test1 = { 
    'width': 23,
    'height': 24,
'block': [
{ 'width': 12, 'height': 11 },
{ 'width': 9, 'height': 10 },
 etc
]
}

The values can be obtained as follows:

self.width = test1['width']

But when I move it to an external file I am unable to do this.

test1 = open('test1.py').read()

The above does read in the file but doesn't 'understand' it. I've tried messing around with eval or from test1.py import *, but can't figure it out. What should I do?

PS If you would recommend to store this info in a different way altogether please let me know how & why.

Upvotes: 1

Views: 67

Answers (1)

SuperBiasedMan
SuperBiasedMan

Reputation: 9979

The simplest way, if you're always going to keep both files in the same folder, is using from import at the start of the file.

from filename import variablename

In your case

from test1 import test1

Note that you don't need to have the .py filetype at the end of the filename. This essentially imports the variable from that file into your one and then you can use it as if it was declared in the file where you have the import command.

Upvotes: 4

Related Questions