Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@bboe 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