-2

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,790
  • 2
  • 22
  • 45
  • Possible duplicate of [Getting a list of all subdirectories in the current directory](https://stackoverflow.com/questions/973473/getting-a-list-of-all-subdirectories-in-the-current-directory) – CaptainTrunky Jun 02 '17 at 08:46

2 Answers2

2

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
  • 25,191
  • 47
  • 61
  • 93
Saurabh kukade
  • 1,504
  • 9
  • 21
  • 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
  • 10,166
  • 4
  • 29
  • 58