Ensure that the directory exists before trying to write to the file.

def _ensure_filepath(filename):
        """
        Ensure that the directory exists before trying to write to the file.
        """

        filepath = os.path.dirname(filename)
        if not os.path.exists(filepath):
            os.makedirs(filepath)