-3

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()  
2
  • 1
    This is what lists & dictionaries are for. Commented May 2, 2022 at 15:28
  • Great question! Check out this helpful answer on a similar question How to define variables dynamically in python? Commented May 2, 2022 at 15:28

4 Answers 4

0

Don't. Your code should not rely on dynamically creating variables. Use a container, such as a list.

E.g. vs = [float(line) for line in s]. Now "v1" is at vs[0], "v2" is at vs[1], and so on.

Sign up to request clarification or add additional context in comments.

2 Comments

but this will convert the data into a list and that isn't what I want! I want to store the data into independant variables
@youssef you should not want that. It's bad coding style.
0

This is exactly what lists and arrays are intended for. You can store your data in a list that you can later index at each position, as such:

s = open("Lines_only.txt", "r")
# Initialize a list
data = []
# Populate list
for line in s:
  data.append(line)
# Now you can index into the list to get your data:
print(data[0])
print(data[3])
OUTPUT: 
0.9
-0.43

Comments

-1

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

5 Comments

I don't think you get much value from a dict over a list when the names are just consecutively numbered.
That's true, the idea was just to keep the vx notation, but a list do the job as well
@Xiidref the 2nd one worked ! Thanks a lot but why everyone warns me from using this style?!
@youssef Mostly because it can be really tricky to understand the code later, for example you can have v3 used somewhere in the code but nowhere with v3=... this can make things hard to understand and debug. Also, another point is that there is no IDE that will understand this (at least not in the ones I know) and they will show you an error when using v3 because it can't find any suitable definition.
@Xiidref I got it now ! Many thanks for your help and understanding
-1

The other answers are correct to guide you toward collections. But in those rare cases where you need to create variable names on the fly, you can use attr() for object attributes, and either locals() or globals() for accessing variables through a dictionary interface. Thus:

with open("Lines_only.txt", "r") as s:
    j = 1
    for i in s:
        line = i.strip()
        locals()[f'v{j}'] = float(line)
        j += 1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.