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.

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

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 ?

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(...)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.