-1

Have repository folder in which I have 100 folders of images. I want to iterate over each folder and then do the same over images inside these folders.

for example : repository --> folder1 --> folder1_images ,folder2 --> folder2_images ,folder3 --> folder3_images

May someone know elegante way of doing it?

P.S my OS is MacOS (have .DS_Store files of metadata inside)

Ivan Shelonik
  • 1,958
  • 5
  • 25
  • 49

3 Answers3

3

You can do use os.walk to visit every subdirectory, recursively. Here's a general starting point:

import os
parent_dir = '/home/example/folder/'

for subdir, dirs, files in os.walk(parent_dir):
    for file in files:
        print os.path.join(subdir, file)

Instead of print, you can do whatever you want, such as checking that the file type is image or not, as required here.

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
Saurabh kukade
  • 1,608
  • 12
  • 23
  • Yeah, this great, but I'm stucked with moving up one folder from the list of folders that I have. That's the problem I have dirs = ['folder1', 'folder2', 'folder3']. How to move up inside it? – Ivan Shelonik Jun 02 '17 at 09:25
  • I dont get it. can you please expalin this "problem I have dirs = ['folder1', 'folder2', 'folder3']. How to move up inside it?" – Saurabh kukade Jun 02 '17 at 10:45
1

Have a look at os.walk which is meant exactly to loop through sub-directories and the files in them.

More info at : https://www.tutorialspoint.com/python/os_walk.htm

Ofer Sadan
  • 11,391
  • 5
  • 38
  • 62
1

Everyone has covered how to iterate through directories recursively, but if you don't need to go through all directories recursively, and you just want to iterate over the subdirectories in the current folder, you could do something like this:

dirs = list(filter(lambda d: os.path.isdir(d), os.listdir(".")))

Annoyingly, the listdir function doesn't only list directories, it also lists files as well, so you have to apply the os.path.isdir() function to conditionally 'extract' the elements from the list only if they're a directory and not a file.

(Tested with Python 3.10.6)

Raleigh L.
  • 599
  • 2
  • 13
  • 18