Get full path for files within subdirectories

I am having some issue finding all the files (in this case .wav) within subdirectories within a directory.

Is there a simple way to do this? Below is what I have that only works on files within current working directory

  1 import os
  2 path = os.path.expanduser(os.getcwd())
  3
  4 for filename in os.listdir(path):
  5     if (filename.endswith(".wav")):
  6         if (filename.endswith("d.wav")):
  7             continue
  8         else:
  9             os.system("echo {}".format(filename))

Try os.walk: https://www.tutorialspoint.com/python/os_walk.htm

It walks the whole directory structure up and down.

2 Likes

Something I wrote several years ago that might help:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# catwalk - learning how to climb trees. ;-)
# Written by Kevin Cole <kjcole@gri.gallaudet.edu> 2009.07.01
#

# This little ditty does a recursive listing of the contents of
# the argument given in os.walk(), but only prints out those
# matching pattern (e.g., files ending in .asc)

import os
import re
from   os.path import join, expanduser


def fetch(root, pattern):
    """Returns a list of fully qualified paths
    under 'root' matching regex 'pattern'"""
    targets = re.compile(pattern)            # File regex
    for path, dirs, files in os.walk(root):
        for file in files:
            if not targets.search(file):     # Skip files that don't match
                continue
            yield join(path, file)           # Like "%s/%s" % (path, file)


def main():
    """Usage: python3 catwalk.py "/starting/path" "file_extension_regex" """
    import sys
    tree = expanduser(sys.argv[1])         # e.g. "~/yada-yada/"
    files = r"\.{0}$".format(sys.argv[2])  # e.g. "csv"
    for nextfile in fetch(tree, files):
        print(nextfile)


if __name__ == "__main__":
    main()
2 Likes

That looks like a great solution :slight_smile:

1 Like

Lots to learn from that. I definitely need to look into re.search(), etc. Thanks!

Thanks Marc, I knew there had to be an equiv for the bash for file in "$1"/*

Ah yes, the wonderful world of RegEx. I always find myself falling back to https://regexr.com/ to test them, since Iā€™m hardly an expert.