I am trying to populate a list called images
with files that have the extensions '.png'
, '.jpg'
or 'jpeg'
in a one line for loop. I tried this by using the logical or
operator but that only resulted in an empty list.
images = [i for i in os.listdir('.') if i[-4:] == ('.png' or '.jpg' or 'jpeg')]
How do I check to see if '.png'
, '.jpg'
or 'jpeg'
are the last 4 characters of the file while keeping it all in a one line for loop?
Using or
is a boolean expression which checks if any value in the expression evaluates to True
.
i[-4:] == ('.png' or '.jpg' or 'jpeg')
evaluates if i[-4:]
is equal to:
('.png' or '.jpg' or 'jpeg')
which checks if each value is True
and returns the first True
value or the last value if there are no True
values. In this case they all evaluate to True
as only empty strings evaluate to False
so '.png'
is the result of the expression.
You can fix this by doing
[i for i in os.listdir('.') if i[-4:] in ('.png', '.jpg', 'jpeg')]
Or a better way
[i for i in os.listdir('.') if os.path.splitext(i)[1] in ('.png','.jpg','.jpeg')]