Dax Feliz
Dax Feliz

Reputation: 12939

Python- Writing all results from a loop to a variable

I have a .txt file with dozens of columns and hundreds of rows. I want to write the results of the entirety of two specific columns into two variables. I don't have a great deal of experience with for loops but here is my attempt to loop through the file.

a = open('file.txt', 'r') #<--This puts the file in read mode

header = a.readline() #<-- This skips the strings in the 0th row indicating the labels of each column

for line in a:
    line = line.strip() #removes '\n' characters in text file
    columns = line.split() #Splits the white space between columns
    x = float(columns[0]) # the 1st column of interest  
    y = float(columns[1]) # the 2nd column of interest
    print(x, y)
f.close()

Outside of the loop, printing x or y only displays the last value of the text file. I want it to have all the values of the specified columns of the file. I know of the append command but I am unsure how to apply it in this situation within the for loop.

Does anyone have any suggestions or easier methods on how to do this?

Upvotes: 1

Views: 4465

Answers (2)

asdqzxs
asdqzxs

Reputation: 1

Your code only binds the value of the last element. I'm not sure that is your entire codes, but if you want to keep add the values of the column, I would suggest appending it to the array then print it outside of loop.

listx = []
listy = []
a = open('openfile', 'r')
#skip the header
for line in a:
    #split the line
    #set the x and y variables.
    listx.append(x)
    listy.append(y) 
#print outside of loop.

Upvotes: 0

Mike M&#252;ller
Mike M&#252;ller

Reputation: 85622

Make two lists x and y before you sart the loop and append to them in the loop:

a = open('file.txt', 'r') #<--This puts the file in read mode

header = a.readline() #<-- This skips the strings in the 0th row indicating the labels of each column

x = []
y = []
for line in a:
    line = line.strip() #removes '\n' characters in text file
    columns = line.split() #Splits the white space between columns
    x.append(float(columns[0])) # the 1st column of interest  
    y.append(float(columns[1])) # the 2nd column of interest

f.close()

print('all x:')
print(x)
print('all y:')
print(y)

Upvotes: 1

Related Questions