Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
265 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...