2012-10-23 71 views
1

这是一个衍生自this question。在那一个,下面一行在python脚本出现:python - 从文件中读取几列

c1,c2 = [float(x) for x in line.split()] #convert line into 2 floats and unpack 

中读取数据文件有两列时。

现在,我真正数据文件有31列,我需要当我尝试最简单的(和最丑陋的)方法,在不断升级的该行使用的列28和31,而不是1和2:

c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11,c12,c13,c14,c15,c16,c17,c18,c19,c20,c21,c22,c23,c24,c25,c26,c27,c28,c29,c30,c31 = [float(x) for x in line.split()] 

我得到的错误:

ValueError: too many values to unpack 

我怎样才能正确地读我的文件中的所有列?

+0

是否所有行都有31列?如果这些行“锯齿状”(有些列少于或多于31列),则此方法将失败。 –

回答

2

另一种方法数组:

cols = [float(x) for x in line.split()] 
c28, c31 = cols[27], cols[30] 

所以,总体格局将类似于:

with open('<file name here>') as source_file: 
    for line in source_file: 
     cols = [float(x) for x in line.split()] 
     c28, c31 = cols[27], cols[30] 
+0

太棒了,我选择这个主要是因为它清楚地表明数组从'0'开始,这不是一件小事(不知道这给了我奇怪的结果)谢谢! – Gabriel

1
cols = [float(x) for x in line.split()] 
for i in len(cols): 
    print i, cols[i] 

没有必要实例N个变量,只需使用你在阅读文件

for循环在这种情况下,可以帮助你看到你真的有多少价值有