Created
September 1, 2013 23:57
-
-
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).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.