Skip to content

Instantly share code, notes, and snippets.

@adamdoupe
Created September 1, 2013 23:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamdoupe/6408104 to your computer and use it in GitHub Desktop.
Save adamdoupe/6408104 to your computer and use it in GitHub Desktop.
Function that abstracts the access pattern of os.makedirs (run this function on every directory in this directory structure).
from os import path
def for_all_in_path (name, fun):
"""
Iterator to run the given function (fun) on each directory in the given path (name).
Example: for_all_in_path("test/adam/example", fun) would call:
fun("test")
fun("test/adam")
fun("test/adam/example")
"""
head, tail = path.split(name)
if not tail:
head, tail = path.split(head)
if head and tail:
for_all_in_path(head, fun)
fun(name)
@bboe
Copy link

bboe commented Sep 2, 2013

The code as-is assumes name is a directory. You may want to handle the case where the last component is a file in which it would operate on the file's ancestor directories. The name is also slightly ambiguous as to whether it works on the path components (as it does in this case) or on all the files in the directory. It's less ambiguous as for_all_on_path though still not super intuitive. Looks great otherwise.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment