def replace_ext(filename, oldext, newext):
    """Safely replaces a file extension new a new one"""

    if filename.endswith(oldext):
        return filename[:-len(oldext)] + newext
    else:
        raise Exception("file '%s' does not have extension '%s'" %
                        (filename, oldext))