def file_w_create_directories(filepath):
    """
    Recursively create some directories if needed so that the directory where
    @filepath must be written exists, then open it in "w" mode and return the
    file object.
    """
    dirname = os.path.dirname(filepath)

    if dirname and dirname != os.path.curdir and not os.path.isdir(dirname):
        os.makedirs(dirname)

    return open(filepath, 'w')
Recursively create some directories if needed so that the directory where
    @filepath must be written exists, then open it in "w" mode and return the
    file object.