Python 2.7 Python—将循环中的所有结果写入变量

Python 2.7 Python—将循环中的所有结果写入变量,python-2.7,for-loop,append,text-files,Python 2.7,For Loop,Append,Text Files,我有一个.txt文件,有几十列和数百行。我想将两个特定列的全部结果写入两个变量。我对for循环没有太多的经验,但下面是我对循环文件的尝试 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

我有一个
.txt
文件,有几十列和数百行。我想将两个特定列的全部结果写入两个变量。我对for循环没有太多的经验,但下面是我对循环文件的尝试

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()

a=open('file.txt','r')#您的代码只绑定最后一个元素的值。我不确定这是您的全部代码,但如果您想继续添加列的值,我建议将其附加到数组中,然后在循环外部打印它

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.

在插入循环并附加到循环中之前,先列出两个列表
x
y

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)

a=open('file.txt','r')#太棒了!我不知道事情有那么简单。非常感谢@MikeMüller!这正是我想要的。