Search code examples
python-3.xloopssdkqr-codetry-except

Loop is stopping when a file cannot be scanned instead of skipping and moving to the next file in Python?


I am using DBR package in Python to scan the files and decode the barcodes. Problem is that the loop stops when it sees an error. I want it to skip the file if there is an error and decode the next files until all the files are completed (either scanned or error). This is part of the code that I am using.

image_path = 'C:/Users/username/Samples/'
image = glob.glob(image_path + '*')

barcodes = {}
try: 
    
    for i,v in enumerate(image):    
        results = reader.decode_file(v)
    
        for result in results:
            #if len(result.barcode_text) <= 31: 
            #barcodes[v.rsplit('\\',1)[1]] = result.barcode_text
            barcodes[v.replace(image_path, '')] = result.barcode_text 
            print(v.replace(image_path, ''))  
            
                           
    barcodes_df = pd.DataFrame(list(barcodes.items()), columns=['filename', 'barcode'])
    
    del reader

# except:
#     #print(e)
#     pass

except BarcodeReaderError as bre:
    print(bre) 

I tried except pass but that did not do what I want. Can anyone help please? I cannot use any other library so it has to be DBR.

This is the error I get when it reaches to the file that cannot be scanned.

TypeError: 'NoneType' object is not iterable

Solution

  • I was able to ignore the issue using the following code. I had to assign empty list to the variable "results" basically when it is empty.

    image_path = 'C:/Users/username/Samples/'
    image = glob.glob(image_path + '*')
    
    barcodes = {}
    try: 
        
        for i,v in enumerate(image):    
            results = reader.decode_file(v)
    
            if results is None:
                results = []
        
            for result in results:
                #if len(result.barcode_text) <= 31: 
                #barcodes[v.rsplit('\\',1)[1]] = result.barcode_text
                barcodes[v.replace(image_path, '')] = result.barcode_text 
                print(v.replace(image_path, ''))  
                
                               
        barcodes_df = pd.DataFrame(list(barcodes.items()), columns=['filename', 'barcode'])
        
        del reader
    
    # except:
    #     #print(e)
    #     pass
    
    except BarcodeReaderError as bre:
        print(bre)