在python中使用readlines?第一次

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12996220/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:22:26  来源:igfitidea点击:

Using readlines in python? First time

pythonreadlines

提问by user1762768

I have a text file with columns of data and I need to turn these columns into individual lists or arrays. This is what I have so far

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

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

When I run this I get IndexError: list index out of range.

当我运行这个时,我得到IndexError: list index out of range.

Snippet of the data below:

以下数据片段:

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   

I need the first column, if possible to look like this: Data = [16, 17, 18, 20, 21, 22, 24, 25, 26]

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

采纳答案by root

You are getting an empty list Data=[]if you read an empty row. You try to get the first element from the list using Data[0],but because it's an empty list it doesn't have an element at position 0, so you get an IndexError.

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

This will print out the Dataif IndexErroroccours - you can see yourself that it prints an empty list:

这将打印出Dataif IndexErroroccous - 您可以看到它打印了一个空列表:

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

You can use the withstatement to open the file, that automatically closes the file after being processed. Also you can loop over the file itself, without using readlines().

您可以使用该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'

EDIT: You are better of using the csv module:

编辑:您最好使用 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']

回答by Inbar Rose

use with for filehandlers.

用于文件处理程序。

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

you index error comes from trying to access Dataat the [0]location. which simply means your line was empty.

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

you should run a quick check before parsing the line...

您应该在解析该行之前进行快速检查...

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

回答by okan kilic

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

I hope that it solves your problem.

我希望它能解决你的问题。

回答by user4730171

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;

回答by user4816019

#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

回答by user4816019

#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; 

回答by kevin

I would avoid using Data[0] or row[0], instead, I would use ''.join(Data) or ''.join(row) to avoid empty list (list index out of range error).

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