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())
  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:

It walks the whole directory structure up and down.


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 <> 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     # Skip files that don't match
            yield join(path, file)           # Like "%s/%s" % (path, file)

def main():
    """Usage: python3 "/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):

if __name__ == "__main__":

That looks like a great solution :slight_smile:

1 Like

Lots to learn from that. I definitely need to look into, 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 to test them, since Iā€™m hardly an expert.