def set_key(dotenv_path, key_to_set, value_to_set, quote_mode="always"):
    # type: (_PathLike, Text, Text, Text) -> Tuple[Optional[bool], Text, Text]
    """
    Adds or Updates a key/value to the given .env

    If the .env path given doesn't exist, fails instead of risking creating
    an orphan .env somewhere in the filesystem
    """
    value_to_set = value_to_set.strip("'").strip('"')
    if not os.path.exists(dotenv_path):
        logger.warning("Can't write to %s - it doesn't exist.", dotenv_path)
        return None, key_to_set, value_to_set

    if " " in value_to_set:
        quote_mode = "always"

    if quote_mode == "always":
        value_out = '"{}"'.format(value_to_set.replace('"', '\\"'))
    else:
        value_out = value_to_set
    line_out = "{}={}\n".format(key_to_set, value_out)

    with rewrite(dotenv_path) as (source, dest):
        replaced = False
        for mapping in with_warn_for_invalid_lines(parse_stream(source)):
            if mapping.key == key_to_set:
                dest.write(line_out)
                replaced = True
            else:
                dest.write(mapping.original.string)
        if not replaced:
            dest.write(line_out)

    return True, key_to_set, value_to_set

    Adds or Updates a key/value to the given .env

    If the .env path given doesn't exist, fails instead of risking creating
    an orphan .env somewhere in the filesystem
    
dynaconf/vendor/dotenv/main.py