【发布时间】:2017-06-11 06:43:33
【问题描述】:
我有一个包含数十列和数百行的.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()
在循环之外,打印x 或y 只显示文本文件的最后一个值。我希望它具有文件指定列的所有值。我知道 append 命令,但我不确定如何在这种情况下在 for 循环中应用它。
有没有人对如何做到这一点有任何建议或更简单的方法?
【问题讨论】:
标签: python-2.7 for-loop append text-files