Python FTP – CD With Creating Missing Directories

I’m working on continuous integration and writing a Python script to upload changes via ftp to the production server on every commit. As part of this I needed a way to change to a directory and if any of the directories in the path don’t exists, just create them. Since I’m new to Python I turned to Google but haven’t found an easy solutions so I wrote one. Recursion FTW!

from ftplib import FTP

ftp = FTP('domain.com', 'username', 'password')

def cdTree(dir):
    if dir != "":
        try:
            ftp.cwd(dir)
        except:
            cdTree("/".join(dir.split("/")[:-1]))
            ftp.mkd(dir)
            ftp.cwd(dir)

cdTree("/this/is/an/example")

World.Hello()!

Welcome to my blog, The Demeny Den. Here I will share my thoughts about things I find interesting. Thank you Jo-Pa for helping me coming up with the name. :)