extract a column from text file

最后都变了- 提交于 2020-01-17 14:34:29

问题


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


回答1:


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

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.

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.




回答2:


split() whitout any separator information, does the split on spaces:

"1 2 3".split() returns ["1","2","3"]

So be sure to check what separator you are using. Look for str.split.

Also notice that the list is made up of strings, not numeric values.



来源:https://stackoverflow.com/questions/32204038/extract-a-column-from-text-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!