-2

I want to write a code to find all files in subdirectories respectively and then doing one operation for each subdicrectry and then as it goes on..I have came up with below codes but this travers through all files in the directory, but I need to grab all files in particular subdirectory..

for root, dirs, files in os.walk(train_path_healthy):
    for filename in files:
        if (os.path.splitext(os.path.join(root, filename))[1] == ".png"):

Can someone help me how do that in python?

Mahi
  • 97
  • 2
  • 9
  • 1
    Does this answer your question? [How to use glob() to find files recursively?](https://stackoverflow.com/questions/2186525/how-to-use-glob-to-find-files-recursively) – Lescurel Sep 16 '20 at 12:08
  • please elaborate your use case clearly which will help us to help you better. And rather than using for loop it would be better if you use a recursive function – dvijparekh Sep 16 '20 at 12:08
  • `train_path_healthy` this variable has your directory defined. If you only want to get the files of a particular subdirectory you need to change this variable to your subdirectory. – Tin Nguyen Sep 16 '20 at 12:15

1 Answers1

0

One potential way is to utilize glob module for this and other related tasks.

Test case:

A folder test contains 3 subdirectories 1,2 and 3. Each of the subdirectory contains 2 png and txt files each.

Code:

import os, glob

path = "test"
for root, dirs, files in os.walk(path, topdown=True):
   for name in dirs:
     print(glob.glob(root + '/' +  name + '/*.png'))

Output:

['test/1/2.png', 'test/1/1.png']
['test/3/4.png', 'test/3/5.png']
['test/2/4.png', 'test/2/3.png']
Grayrigel
  • 3,474
  • 5
  • 14
  • 32