def set_file_encoding(p, encoding):
    """
    Set the encoding of the file.
    :param p: path to the file
    :type p: str
    :param encoding: encoding to set
    :type encoding: str
    """
    fe = get_encoding_of_file(p)
    if fe is None:
        # we can add the encoding
        to_add = "# -*- coding: {} -*-\n".format(encoding)
        with open(p, "r") as fin:
            lines = fin.readlines()
        if len(lines) == 0:
            # file empty, but we should still add
            lines = [to_add]
        elif lines[0].startswith("#!"):
            # add after shebang
            lines.insert(1, to_add)
        else:
            # add at start
            lines.insert(0, to_add)
        with open(p, "w") as fout:
            fout.write("".join(lines))
    else:
        # we need to overwrite the encoding
        to_add = "# -*- coding: {} -*-\n".format(encoding)
        with open(p, "r") as fin:
            lines = fin.readlines()
        was_set = False
        for i in range(len(lines)):
            line = lines[i]
            if is_encoding_line(line):
                # replace line
                lines[i] = line
                was_set = True
                break
        if not was_set:
            # we should still set the encoding
            if lines[0].startswith("#!"):
                # add after shebang
                lines.insert(1, to_add)
            else:
                # add at start
                lines.insert(0, to_add)

    Set the encoding of the file.
    :param p: path to the file
    :type p: str
    :param encoding: encoding to set
    :type encoding: str
    
tools/encoding_utils.py