Saturday, July 11, 2009

Create directory in python snippet

I've been writing more python these days, and I ran into a need for a method that would recursively create directories if they don't yet exist. I'm sure many other people have written this same thing better, but I thought I'd post it in case anyone out there found it useful:

import os

def CreateDirectory(dir):
"""
Method that creates the directory structure given.
This will create directories recursively until the given dir exists.
"""
if dir[-1] == os.sep:
dir = dir[0:-1]
if not os.path.isdir(dir):
if not os.path.isdir(dir[0:dir.rfind(os.sep)]):
CreateDirectory(dir[0:dir.rfind(os.sep)])
os.mkdir(dir)

Advertising FAIL of the day...


Really? WTF.

I'm not sure what's stranger -- the fact that this site actually exists, or the fact they paid for this advertising.