从文本文件中提取一列 [英] extract a column from text file

查看:119
本文介绍了从文本文件中提取一列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个25列的文本文件(大量的浮点数).我想提取第14列并除以第15列.我无法提取这两列.
代码:

I have a a text file (huge amount of float numbers) with 25 columns. I want to extract column 14 and divide it by column 15. I could not extract this two columns.
Codes:

with open('sample for north.txt') as infile:
    for line in infile:
        print(line.split()[13])

错误:列表索引超出范围

Error : list index out of range

推荐答案

由于没有足够的列(至少在给定的行上),您将收到错误Error : list index out of range.最好检查一下,类似于以下内容:

You are getting the error Error : list index out of range because there aren't enough columns (at least on the given line). It's better to check, something along this line:

with open('sample for north.txt') as infile:
    for line in infile:
        parts = line.split()
        if len(parts) > 13: # or whatever is appropriate
           print(parts[13])

说明:分割行时,它会返回项目列表.例如,如果有3列,则.split()将返回包含3个项目的列表.列表的长度随数据的变化而变化.

Explanation: when you split a line, it returns a list of items. E.g., if there were 3 columns, .split() would return list containing 3 items. The length of the list varies with each line of course depending on the data.

您的代码假定给定行上总是有所需的项目数,并尝试访问索引13的列表中的项目.但是,数据文件中至少应有一行不是该行.情况,这就是您的代码崩溃的原因.因此,最好在尝试访问列表中的给定索引之前先检查列表的长度.

Your code assumed that there always were the required number of items on a given line and tried to access the item in the list at index 13. However, there must be at least one line in your data file where this is not the case, which is why your code crashed. Therefore it's better to examine the length of the list before trying to access a given index in the list.

即,我将线分成部分",然后在尝试访问它之前检查了它的长度.

I.e., I split the line into its "parts", and then examined its length before trying to access it.

这篇关于从文本文件中提取一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆