简体   繁体   中英

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

what about something like this:

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

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, eg the one in the standard library .

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']
for line in open("file"):
    try:
        s=line.split(";")[2]
    except: pass
    else:
        print s

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM