2012-10-21 24 views
7

我有一个数据列的文本文件,我需要把这些列变成单个列表或数组。 这是我迄今为止在python中使用readlines?第一次

f = open('data.txt', 'r') 
temp = [] 
for row in f.readlines(): 
    Data = row.split() 
    temp.append(float(Data[0])) 

当我运行此我得到IndexError: list index out of range

下面的数据的片段:

16 0.2000 
17 0.3000 
18 0.4000 
20 0.5000 
21 0.6000 
22 0.7000 
24 0.8000 
25 0.9000 
26 1.000 

我需要的第一列,如果可能看起来像这样: 数据= [16,17,18,20,21,22,24,25, 26]

+4

['csv'](http://docs.python.org/library/csv.html)是你的朋友。 –

+1

...不应该为f.readlines()中的行:'或者更简单地'为f中的行吗? – nneonneo

回答

5

如果您读取空行,您将得到一个空列表Data=[]。您尝试使用Data[0]从列表中获取第一个元素,但由于它是空列表,因此它在位置0处没有元素,因此您会得到IndexError

Data=''.split() 

Data[0] 
--------------------------------------------------------------------------- 
IndexError        Traceback (most recent call last) 
<ipython-input-686-0792b03cbbdf> in <module>() 
----> 1 Data[0] 

IndexError: list index out of range 

这将打印出Data如果IndexError occours - 你可以看到自己,它打印一个空列表:

f=open('file','r') 
temp = [] 
for row in f.readlines(): 
    Data = row.split() 
    try: 
     temp.append(float(Data[0])) 
    except IndexError: 
     print Data 

可以使用with语句来打开文件时,自动关闭文件处理完毕后。您也可以循环播放文件本身,而无需使用readlines()

with open(file,'r') as f:   
    for row in f: 
     Data = row.split() 
     try: 
      print Data[0] 
     except IndexError: 
      print 'You have an empty row' 

编辑:您是使用CSV模块的更好:

import csv 
with open('file.csv', 'rb') as f: 
    reader = csv.reader(f, delimiter=' ') 
    print [row[0] for row in reader if len(row)] 
>>> 
['16', '17', '18', '20', '21', '22', '24', '25', '26'] 
+0

非常感谢您的反馈和建议。有没有一种方法可以将数据转换为像这样的列表形式:Data = [0,1等]? – user1762768

+0

我只是想把数据放到列表中,因为我需要使用它来执行线性插值。如果我使用你建议的最后一种方法,(使用'with')是否会给我一个列表,以便稍后用于插值? 0,1等分别被导入 – user1762768

+0

,如果你想使用插值看看大熊猫库(它可以导入消法从CSV数据)的数据值只是一个例子,这是一个使用熊猫作为一个插值例回答以前的问题http://stackoverflow.com/questions/12982792/interpolate-number-sequence/12983037#12983037 – root

2

与filehandlers使用。

with open('path/to/file', 'r') as f: 
    for line in f: 
     # code. 

您指数误差来自试图在[0]位置访问Data。 这只是表示你的行是空的。

你应该分析前行运行快速检查...

if len(Data): 
    #code 
else: 
    #empty line? 
+1

在Python中,最好编写'if len(Data):'而不是'if len(Data)> 0:'。 –

+0

@布尔汉哈立德 - 你不能那么做,如果数据:? – root

+0

@root否,因为空列表仍然存在。 '>>> A = []''>>>打印了''[]' –

0
f = open('data.txt', 'r') 
temp = [] 
for row in f.readlines(): 
    items = row.split(',') 
    temp.append(unicode(items[0])) 

我希望它可以解决你的问题。

0
def cal(num_list): 
    x = 1; 
    z = 0; 
    while True: 
     list1 = list(str(x)) 
     list2 = [int(a) for a in list1] 

     for i in range(len(list2)): 
      for j in range(10): 
       if(list2.count(j) > num_list[list2[i]]): 
        z = 1; 
        break; 
     if(z == 1): 
      save(x); 
      break;  
     x = x + 1; 
0
#matrix A to B 
def show(): 
    global string_final,list_2,tot 
    index=matrix_1.index(num) # finding index of num 

    length=n 
    j=(index)%length # the column positon 
    i=index/length # the row position 

    list_1=[] 
    for a in range(length): 
     lis=[] 
     for b in range(length): 

      lis.append(matrix_1.pop(0)) #pop the first element and append the list 

     list_1.append(lis) 

    tot=0 
    list_2=[] 

    for a in range(i+1): 
     for b in range(j+1): 
      tot=tot+list_1[a][b] # add the numbers 
      list_2.append(list_1[a][b]) #append to list 
      if(b!=length): 
       list_2.append(" ") #append space 
     list_2.append("\n") 
    string_final="".join([str(a) for a in list_2]) #list to string 


    print "matrix B\n",string_final,"\nx: ",str(num),"\nn: ",str(n)+"\ntotal: "+str(tot) # print the result 
+0

#mat A到b DEF saveFile的(): 文件=打开( “matrix2.txt”, “W”) file.write( “matrixB \ n” + string_final + “\ NX:” + str(num)+“\ nn:”+ str(n)+“\ ntotal:”+ str(tot)) file.close(); X = 1 而X == 1: getInput() 如果(N <=0 or n> = 20):#检查为n个 打印 “输入正确的N” 破 IF(LEN(matrix_1)= N * N或LEN(集(matrix_1))= LEN(matrix_1)):#检查输入的好不好 打印 “输入错误” 破 如果(对于在matrix_1集([99> A> 9 ])#= {True}):#检查n的值 print“enter suitable number” break show() saveFile() x = x + 1; – user4816019

+0

注释破坏代码格式,特别是在空白显示语言中。请[编辑]您的答案以包含附加代码。 –

0
#matrix add zero 
def get(): 
    global b_no 
    num_list=[]; 
    file=open("matrix.txt","r"); 
    for i in file: 
     b_no=0 
     if(len(i.split())==1): #check length is 1 or not 
      n=int(i)#string to int 
     else: 
      temp=i.split(); 
      if(len(temp)!=n): 
       b_no+=1 
       break 
      temp=[0]+[int(a) for a in temp]+[0] #add zero at first and last 
      num_list.append(temp); 

    zero_list=[] 

    for i in range(n+2): 
     zero_list.append(0)   #append zero 
    num_list.insert(0,zero_list) 
    num_list.insert(n+1,zero_list) 
    return num_list,n; 
+0

#mat add zero#def cal(): list1 = []; 有效范围内的行(1,N + 1): 有效范围内的栏(1,N + 1): TOT = 0; count = 0;对于范围(-1,2)中的m: 对于范围(-1,2)中的p: 如果(num_list [row + m] [col + p] == 0): count = count + 1; tot = tot + num_list [row + m] [col + p]; if(count!= 0): tot = tot /(9-count); 否则: TOT = TOT/9 list1.append(STR(TOT)+”“); list1.append(“\ n”); print“”.join([str(a)for a in list1]) – user4816019

+0

x = 1; 而x == 1: num_list,n = get(); 如果(N> 20或正<3): 打印 “n应3和20之间的” 如果(b_no 破 != 0): print“enter correctly” break cal() x = x + 1; – user4816019

+1

你知道有一个*编辑*选项,对吗? – livibetter

0

我会避免使用Data [0]或行[0],相反,我会用 ''。加入(数据)或 ''。加入(行),以避免空列表(列表索引超出范围错误)。