Handle Exception in Python

Question:

Code:

genders=[]
      for image in os.listdir('Face'):
        try:
          gender = int(image.split('_')[1])
        except ValueError:
          pass
      genders.append(gender)

Trying to add int values of string in list.
Raises Value error

ValueError: invalid literal for int() with base 10: ”

so for example : imageName_1 get that one and add to a list. but sometimes after _ there is no number. so i want to catch that image and delete it but don’t want to stop the iteration.

Asked By: tornike

||

Answers:

Using continue statement will allow you to continue iteration.

genders=[]
for image in os.listdir('Face'):
   try:
       gender = int(image.split('_')[1])
   except ValueError:
       continue
   genders.append(gender)
Answered By: sowwic

gender is defined in the try clause only, so you can’t append it to genders, and you don’t need to (because you want to delete the file), so this line should be in the try clause also:

genders=[]
for image in os.listdir('Face'):
    try:
        gender = int(image.split('_')[1])
        genders.append(gender)
    except ValueError:
        # delete file
        os.remove(image)
Answered By: user107511

Maybe a small change in the code will work

genders=[]
    for image in os.listdir('Face'):
        try:
            gender = int(image.split('_')[1])
            genders.append(gender)
        except ValueError:
            pass
  
Answered By: Aaryan Ahuja
import os
genders=[]
for image in os.listdir('Face'):
  try:
    genders.append(int(image.split('_')[1]))
  except (ValueError, IndexError):
    try:
      os.remove(image)
    except OSError:
      pass
Answered By: user2668284
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.