【问题标题】:Using readlines in python? First time在python中使用readlines?第一次
【发布时间】:2012-10-11 08:45:30
【问题描述】:

我有一个包含数据列的文本文件,我需要将这些列转换为单独的列表或数组。 这就是我目前所拥有的

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]

【问题讨论】:

  • csv 是你的朋友。
  • ...这不应该是for row in f.readlines(): 还是更简单的for row in f

标签: python readlines


【解决方案1】:

如果您读取空行,您将得到一个空列表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

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

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']

【讨论】:

  • 非常感谢您的反馈和建议。有没有办法让我将数据变成这样的列表形式:Data = [0, 1, etc]?
  • 我只是想将数据放入一个列表中,因为我需要使用它来执行线性插值。如果我使用您建议的最后一种方法,(使用'with')会给我一个列表,我可以稍后在我的插值中使用? 0,1 等只是导入数据值的示例
  • 如果您想使用插值,请查看 pandas 库(它可以直接从 csv 导入数据),这里有一个插值示例,使用 pandas 作为对上一个问题的回答 stackoverflow.com/questions/12982792/…跨度>
  • 好吧,再问一个问题,如果我想对数据中的其他列做同样的事情,这会起作用吗?
  • 是的,它会的。只需将 row[0] 更改为 row[1],如果您的行具有第一个值而不是第二个值,则您可能需要添加 if len(row)>1 以避免索引错误。
【解决方案2】:

用于文件处理程序。

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

您的索引错误来自尝试在[0] 位置访问Data。 这只是意味着您的行是空的。

您应该在解析该行之前运行一个快速检查...

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

【讨论】:

  • 在Python中,最好写if len(Data):而不是if len(Data) &gt; 0:
  • @Burhan Khalid -- 如果数据:你就不能这样做吗?
  • @root 否,因为仍然存在一个空列表。 &gt;&gt;&gt; a=[]&gt;&gt;&gt; print a[]
  • @Inbar Rose -- >>> if a: ... print 'foo' ... else: print 'bar' ... bar
【解决方案3】:
f = open('data.txt', 'r')
temp = []
for row in f.readlines():
    items = row.split(',')
    temp.append(unicode(items[0]))

希望它能解决您的问题。

【讨论】:

    【解决方案4】:
    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;
    

    【讨论】:

      【解决方案5】:
      #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; 
      

      【讨论】:

      • #mat 加零# def cal(): list1=[];对于范围内的行(1,n+1):对于范围内的列(1,n+1):tot=0;计数=0;对于范围内的 m (-1,2): 对于范围内的 p (-1,2): if(num_list[row+m][col+p]==0): count=count+1; tot=tot+num_list[行+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])
      • x=1;而 x==1: num_list,n=get(); if(n>20 or n
      【解决方案6】:
      #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
      

      【讨论】:

      • #mat A to b def saveFile(): file=open("matrix2.txt","w") file.write("matrixB\n"+string_final+"\nx: "+str (num)+"\nn: "+str(n)+"\ntotal: "+str(tot)) file.close(); x=1 while x==1: getInput() if(n=20): #check for the n print "enter correct n" break if(len(matrix_1)!=n*n or len (set(matrix_1))!=len(matrix_1)): # 检查输入是否正常 print "wrong input" break if(set([99>a>9 for a in matrix_1])!={True}) :# 检查 n 的值 print "enter proper number" break show() saveFile() x=x+1;
      • 注释会破坏代码格式,尤其是在空格有效的语言中。请edit您的答案包括附加代码。
      【解决方案7】:

      我会避免使用 Data[0] 或 row[0],而是使用 ''.join(Data) 或 ''.join(row) 来避免空列表(列表索引超出范围错误)。

      【讨论】:

        猜你喜欢
        • 2015-03-28
        • 1970-01-01
        • 1970-01-01
        • 2011-04-29
        • 1970-01-01
        • 2012-04-29
        • 1970-01-01
        • 1970-01-01
        • 2021-03-07
        相关资源
        最近更新 更多