1

I have the following lines in a file where I want to take the third column; In the file I don't have the numbers column:

  1. Red; Blue; Green; White; Orange;
  2. Green; White; Orange;
  3. Blue; Green; White;
  4. Red; Blue; Green; White;
  5. Blue; Green; White; Orange;
  6. Orange
  7. Green; White; Orange;
  8. White; Orange
  9. Green;

I used this code line to do that:

lines = i.split(";")[2]

The problem is that some of the lines have only one column or two, so it gives me 'index out of range' error. Please tell me how to go about this problem?

thanks a lot Adia

1
  • well, what do want to do when there isn't enough columns? Commented Oct 8, 2010 at 14:07

4 Answers 4

2

what about something like this:

cols = i.split(";")
if (len(cols) >= 3):
    lines = cols[2]
else:
    #whatever you want here
Sign up to request clarification or add additional context in comments.

Comments

2

The simple solution is to check the number of columns and ignore lines with less than three columns.

third_columns = []
with open("...") as infile:
    for line in infile:
        columns = line.split(';')
        if len(columns) >= 3:
            third_columns.append(columns[2])

And if you parse CSV (seems like you do), you better use one of the numerous existing CSV parsers, e.g. the one in the standard library.

Comments

1

use a slice instead of an index.

>>> with open('test.txt') as f_in:
...     column3 = (line.split(';')[2:3] for line in f_in)
...     column3 = [item[0] for item in column3 if item]
... 
>>> column3
[' Green', ' Orange', ' White', ' Green', ' White', ' Orange']

Comments

0
for line in open("file"):
    try:
        s=line.split(";")[2]
    except: pass
    else:
        print s

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.