Reputation: 23
I have a text file, xyz.txt
that has variables, and I want to use those variables, I know how to read them but do not know how to use it and call them when I need it. For example, If in the text file there is x = 123
I would like to be able to call on that variable for use, so if i said print x
it would give me 123
.
text file:
x = 1.000
y = 2.343
z = 3.000
Later on It will have more data.
Upvotes: 0
Views: 7355
Reputation: 80831
A simple way to do it is to load the content of your file and then use execfile(file_content)
, then you will be able to make print x
and it will print the content of x
.
Upvotes: 0
Reputation: 10101
One solution might be using a dictionary:
vars = dict()
with open("file.txt") as f:
for line in f:
eq_index = line.find('=')
var_name = line[:eq_index].strip()
number = float(line[eq_index + 1:].strip())
vars[var_name] = number
print(vars)
And the file.txt
:
a = 1
b = 2
c = 3
d = 4
variable = 5
So, if you want to see the variable
value you just do:
print(vars["variable"])
Upvotes: 4