Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
268 views
in Technique[技术] by (71.8m points)

python - extract a column from text file

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...