0

I have output file like below:

junk
abc 123 xyz test
123 abc test 123
bob ani kepu maro
exist

What i am trying with this file is I am searching kepu is present in column 3 in the file.

I am trying below code:

   name = "kepu"
   with open("listfile.txt") as f:
      for line in f:
         line = line.split(" ")[2]
         line = line.lower()
         if line == name:
            print "Present"
         else:
            print "Not Present"

Since in file does not have equal number of strings, In first line "junk" and last line "exist" contains only one string and trying

line = line.split(" ")[2] 

This is the reason i am getting below error:

 IndexError: list index out of range

I tried removing first and last line that is junk and exist keyword it works. but my output file generation is random.

Please help me what is the best way to find the string is exit in the third column in file.

5 Answers 5

2

Add a check to ensure that the line has at least 3 words:

wordsInLine = line.split(" ")
if len(wordsInLine) > 2:
    if wordsInLine[2].lower() == name:
        print "Present"
     else:
        print "Not Present"
Sign up to request clarification or add additional context in comments.

Comments

1

Or you can throw catch an exception:

name = "kepu"
with open("listfile.txt") as f:
for line in f:
    try:
        line = line.split(" ")[2]
    except IndexError:
        continue
    line = line.lower()
    if line == name:
        print "Present"
    else:
        print "Not Present"

Comments

0

Just do a simple if statement:

name = "kepu"
with open("listfile.txt") as f:
  for line in f:
     if len(line.split(" ")) >= 3:
         line = line.split(" ")[2]
         line = line.lower()
         if line == name:
            print "Present"
         else:
            print "Not Present"

Comments

0

May be you understand the "for line in f" is not clear: you cant true this code ,may be you can find why your problem happend:

 with open("listfile.txt") as f:
...:     for line in f:
...:        print 'line=%s'%line
...:
line=junk
line=abc 123 xyz test
line=123 abc test 123
line=bob ani kepu maro
line=exist

Comments

0

Use regular expressions:

import re

re_kepu = re.compile('^(\w+ ){2}kepu')

with open('listfile.txt', 'r') as f:
    for line in f:
        if re_kepu.match(line):
            print('Present')
            break
    else:
        print('Not present')

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.