how to make variable name dynamic

I have a text file that has data like this:

0.90
0.43
6.03
-0.43
0.9

and I want my program to read the data and store each line in a new variable where the variable name increases automatically like this:

v1 = 0.9
v2 = 0.43
v3 = 6.03
v4 = -0.43
v5 = 0.9

I have tried this but it didn’t work:

s = open("Lines_only.txt", "r")
j = 1
for i in s:
    line = i.strip()
    v[j] = float(line)
    print(v[j])
    j +=1
s.close()  

>Solution :

The proper way to do it would be to use a dictionary rather than declaring variables :

s = open("Lines_only.txt", "r")
j = 1
v_dict = {}
for i in s:
    line = i.strip()
    v_dict[f"v{j}"] = float(line)
    print(v_dict[f"v{j}"] )
    j +=1
s.close() 

#Then here access to the variables using v_dict["v1"], v_dict["v2"], ... 

However, if what you want is really to declare a variable this is possible too (but you should still use the first option if possible)

s = open("Lines_only.txt", "r")
j = 1
v_dict = {}
for i in s:
    line = i.strip()
    globals()[f"v{j}"] = float(line)
    print(globals()[f"v{j}"])
    j +=1
s.close() 

#Then here access to the variables using v1,v2, ... 
sum_result = v1+v2

Leave a Reply