0

I have Folder Named A, which includes some Sub-Folders starting name with Alphabet A. In these Sub-Folders different images are placed (some of the image formats are .png, jpeg, .giff and .webp, having different names like item1.png, item1.jpeg, item2.png, item3.png etc). From these Sub-Folders I want to get list of path of those images which endswith 1. Along with that I want to only get 1 image file format like for example only for jpeg. In some Sub-Folders images name endswith 1.png, 1.jpeg, 1.giff and etc. I only want one image from every Sub-Folder which endswith 1.(any image format). I am sharing the code which returns image path of items (ending with 1) for all images format.

CODE:

enter image description here

1 Answers1

0

here is the code that can solve your problem.

import os
img_paths = []
for top,dirs, files in os.walk("your_path_goes_here"):
    for pics in files:
        if os.path.splitext(pics)[0] == '1':
            img_paths.append(os.path.join(top,pics))
            break
        

img_paths will have the list that you need

it will have the first image from the subfolder with the name of 1 which can be any format.

Incase if you want with specific formats,

import os
img_paths = []
for top,dirs, files in os.walk("your_path_goes_here"):
    for pics in files:
        if os.path.splitext(pics)[0] == '1' and os.path.splitext(pics)[1][1:] in ['png','jpg','tif']:
            img_paths.append(os.path.join(top,pics))
            break

Thanks, to S3DEV for making it more optimized

Tamil Selvan
  • 1,600
  • 1
  • 9
  • 25
  • 1) `os.path.splitext` should be used to split a file name from its extension. 2) There is no need for `continue` at the end of the loop. – S3DEV Dec 09 '21 at 18:54
  • @S3DEV, the question asks for only one image from one subfolder if you read it that's the reason i added that. Also, the `os.path.splitext` and `split('.')` does the same. – Tamil Selvan Dec 09 '21 at 18:56
  • 1
    Then, it should be `break` (to return to the parent loop), should it not? As the the split, `splitext` should be used as a general `split` will fail (in corner cases) for file names such as `this.file.png`. – S3DEV Dec 09 '21 at 19:01
  • 1
    @S3DEV yes you are right it can fail in those corner cases. I will update it the answer accordingly. Thanks for the lesson man – Tamil Selvan Dec 09 '21 at 19:07