0

I'm trying to find a record in a csv file in a nested stucture:

for elem in lstLine[1:]:
    for item in open(fname):      
        lstData = item.rstrip('\n').split(';')
        andexfield = lstData[0]
        if andexfield == elem:
          do bladibla

Now I want ot add error handling:
if no record in fname is found where andexfield == elem
print "Error, no andexfield in fname"
Can I do this with "try" ?
Any help is much appreciated.

3
Contributors
3
Replies
5
Views
4 Years
Discussion Span
Last Post by Gribouillis
0

Use "else" block.

if andexfield == elem:
    do bladibla
else:
    print "Error, no andexfield in fname" 

Error would be more normal to occur before you compare with ==.
Like open file or get index/iterate list lstData[0] lstLine[1:]

0

That wouldn't work there are many records in fname
so it would print error many times or is there somthing wrong with the for each loops ?

0

You can use a boolean flag

for elem in lstLine[1:]:
    with open(fname) as ifh:
        found = False
        for item in ifh:    
            lstData = item.rstrip('\n').split(';')
            andexfield = lstData[0]
            if andexfield == elem:
              found = True
              do bladibla
        if not found:
            print(...)
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.