Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading