Don't forget to also checkout my second blog containing articles to all other related ICT topics!!

Wednesday, May 23, 2012

Mimicking mkdir Unix in Python

I got inspired by a tweet from @paulgreg today: 'Man. I love Unix shell : mkdir -p src/{main,test}/{java,resources} #unix #shell'. I wanted to find out how difficult this would be to implement in Python and here is a first working draft.
import os
from itertools import product

def mkdir(pathExpr):
    """
    example of pathExpr: src/{main,test}/{java,resources}
    creates following folders:
        - src/main/java
        - src/main/resources
        - src/test/java
        - src/test/resources
    """

    for foldercombi in product(*(getFolderParts(expression) for expression in pathExpr.split('/'))):
        dirname =  '/'.join(foldercombi)
        try:
            os.makedirs(dirname)
        except OSError:
            if os.path.exists(dirname):
                pass

def getFolderParts(expression):
    if expression[0] == '{' and expression[-1] == '}':
        return [part for part in expression[1:-1].split(',')]
    else:
        return [expression]

mkdir('C:/tmp/src/{main,test}/{java,resources}')

2 comments:

  1. Really nice!

    However, you don't need using expression[1:length-1], use expression[1:-1] instead.

    ReplyDelete
  2. Yep... you're totally right. Fixed it. Bad habid from programming in javascript ;-)

    ReplyDelete