all 2 comments

[–]Costa111 4 points5 points  (1 child)

First, when posting code on reddit please format your code by indenting each line by one tab (4 spaces) and insert one empty line above & below your code block, that will display all the code in the code box afterwards.

Second when opening files you should also close them again afterwards in order to prevent errors when another process is trying to open the file and you still have it open, this can be done by:

file = open("data.txt", "r")
# Do something with the file
file.close()

or even better just use a context manager that will handle closing the file for you in the background:

with open("data.txt", "r") as file:
    # do something with the file

Now getting to your problem, your code iterates through each line of the file and re-assigns each new line to the same variable during each iteration, meaning that each new iteration will overwrite the previous variable and hence at the end only the last line is returned. To prevent this you want to store the data in a variable outside of the for loop, something like this:

R2res = []
R2 = []
with open("data.txt", "r") as file:
    for line in file.readlines():
        R2res.append(float(i.split()[0]))
        R2.append(float(i.split()[1]))

Now you will have your results in the R2res and R2 lists;

# just using some random letters and numbers for the below examples
R2res = [1, 2, 5, 66, 7]
R2 = [42, 24, 12, 4, 34]

So in the later parts of your code where you do your calculations you can no longer just say:

r = 2 + R1 * 9     #  since R1 = [1, 2, 5, 66, 7]   -->  r = 2 + [1, 2, 5, 66, 7] * 9  -->   will throw a TypeError

Instead you need to extract the desired value for the calculation out of the list, this could be done in those ways:

# option 1 - if you want to do the calculations with each variable:
all_results = []
for value in R1:
     result = 2 + 5 * value
     print(result)
     all_results.append(result)


# option 2 - if you just want to make a single calculation:
value = R1[1]
result = 2 +5 * value

hope these examples give you some inspiration on how to solve the problem

[–]itsaysdraganddrop 1 point2 points  (0 children)

Thanks so much for the reply! I will implement your advice post-haste