Python-将所有结果从循环写入变量

时间:2017-01-25 22:06:47

标签: 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 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()

在循环外部,打印xy仅显示文本文件的最后一个值。我希望它具有该文件的指定列的所有值。我知道append命令,但我不确定如何在for循环中应用它。

有没有人对如何做到这一点有任何建议或更简单的方法?

2 个答案:

答案 0 :(得分:1)

在开始循环之前制作两个列表xy并在循环中追加它们:

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)

答案 1 :(得分:0)

您的代码仅绑定最后一个元素的值。我不确定这是你的整个代码,但如果你想继续添加列的值,我建议将它附加到数组然后在循环外打印。

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.