4m1nh4j1
4m1nh4j1

Reputation: 4356

Read python variables from a file

I would like to read all variables stored in a file like this :

var1=val1
var2=val2
..etc

Is there a way to access to a metadata where I can find and list all variables without knowing their names? In my script I am using execfile("myFile.txt").

Upvotes: 0

Views: 174

Answers (2)

Blake Walsh
Blake Walsh

Reputation: 1561

execfile actually supports what you want to do.

global_vars = {}
local_vars = {}

execfile("myFile.txt", global_vars, local_vars)

# local_vars now contains the variables defined in the file.
print local_vars

Upvotes: 1

e-nouri
e-nouri

Reputation: 2626

You can use eval() to set the variables or you can turn the file to a dictionary, I think the second solution is more safe than the first one ! You can also make a class and use setattr(self, name, value) to attach the variables to that class dynamically and using the parsed strings.

Upvotes: 0

Related Questions