I want to loop through a folder and select all the images inside it. For now I have the following,
import glob
image_list = []
for filename in glob.glob('screen/*.jpg'):
image_list.append(filename)
That is to say, I am able to obtain all the images .jpg
(obviously if I change the extension, then I am able to obtain all the images of that extension). The thing is that in this folder I also have images .png
, is it possible in a loop for
to put two options, or an operator or
? Now I have solved it like this, but I'm sure it can be simplified/optimized.
import glob
image_list = []
for filename in glob.glob('screen/*.jpg'):
image_list.append(filename)
for filename in glob.glob('screen/*.png'):
image_list.append(filename)
Thank you and greetings.
You could loop through the whole folder and use the conditional
if
using the moduleos
(no need to install it, it comes by default with Python):The function
os.listdir()
we pass it a path , and it gives us everything that contains that path , it's like doing als
in Linux or adir
in Windows.Once we have with the function, all the files that are in the directory, we simply select those that interest us, in this case the
.jpg
and the.png