Python function that similar to bash find command

For a search pattern like that, you can probably get away with glob.

from glob import glob
paths = glob('set01/*/*.png')

You can use os.walk to traverse the directory tree. Maybe this works?

import os

for dpath, dnames, fnames in os.walk("."):
  for i, fname in enumerate([os.path.join(dpath, fname) for fname in fnames]):
    if fname.endswith(".png"):
      #os.rename(fname, os.path.join(dpath, "%04d.png" % i))
      print "mv %s %s" % (fname, os.path.join(dpath, "%04d.png" % i))

For Python 3.4+ you may want to use pathlib.glob() with a recursive pattern (e.g., **/*.png) instead:

  • Recursively iterate through all subdirectories using pathlib
  • https://docs.python.org/3/library/pathlib.html#pathlib.Path.glob
  • https://docs.python.org/3/library/pathlib.html#pathlib.Path.rglob

Tags:

Python