Adia
Adia

Reputation: 1211

Python: loop through a file for specific lines

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

Upvotes: 1

Views: 1893

Answers (4)

aaronasterling
aaronasterling

Reputation: 70994

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

Upvotes: 1

ghostdog74
ghostdog74

Reputation: 342323

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

Upvotes: 0

user395760
user395760

Reputation:

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.

Upvotes: 2

Mike Clark
Mike Clark

Reputation: 11959

what about something like this:

cols = i.split(";")
if (len(cols) >= 3):
    lines = cols[2]
else:
    #whatever you want here

Upvotes: 2

Related Questions