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.
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"
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments