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.
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)
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)
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
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
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.
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)
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)
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
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