Writes text to a file. Automatically encodes text as utf8.

    Args:
        fpath (str): file path
        to_write (str): text to write (must be unicode text)
        aslines (bool): if True to_write is assumed to be a list of lines
        verbose (bool): verbosity flag
        onlyifdiff (bool): only writes if needed!
                checks hash of to_write vs the hash of the contents of fpath
        mode (unicode): (default = u'w')
        n (int):  (default = 2)

    CommandLine:
        python -m utool.util_io --exec-write_to --show

    Example:
        >>> # DISABLE_DOCTEST
        >>> from utool.util_io import *  # NOQA
        >>> import utool as ut
        >>> fpath = ut.unixjoin(ut.get_app_resource_dir('utool'), 'testwrite.txt')
        >>> ut.delete(fpath)
        >>> to_write = 'utf-8 symbols Δ, Й, ק, م, ๗, あ, 叶, 葉, and 말.'
        >>> aslines = False
        >>> verbose = True
        >>> onlyifdiff = False
        >>> mode = u'w'
        >>> n = 2
        >>> write_to(fpath, to_write, aslines, verbose, onlyifdiff, mode, n)
        >>> read_ = ut.read_from(fpath)
        >>> print('read_    = ' + read_)
        >>> print('to_write = ' + to_write)
        >>> assert read_ == to_write

def write_to(fpath, to_write, aslines=False, verbose=None,
             onlyifdiff=False, mode='w', n=None):
    """ Writes text to a file. Automatically encodes text as utf8.

    Args:
        fpath (str): file path
        to_write (str): text to write (must be unicode text)
        aslines (bool): if True to_write is assumed to be a list of lines
        verbose (bool): verbosity flag
        onlyifdiff (bool): only writes if needed!
                checks hash of to_write vs the hash of the contents of fpath
        mode (unicode): (default = u'w')
        n (int):  (default = 2)

    CommandLine:
        python -m utool.util_io --exec-write_to --show

    Example:
        >>> # DISABLE_DOCTEST
        >>> from utool.util_io import *  # NOQA
        >>> import utool as ut
        >>> fpath = ut.unixjoin(ut.get_app_resource_dir('utool'), 'testwrite.txt')
        >>> ut.delete(fpath)
        >>> to_write = 'utf-8 symbols Δ, Й, ק, م, ๗, あ, 叶, 葉, and 말.'
        >>> aslines = False
        >>> verbose = True
        >>> onlyifdiff = False
        >>> mode = u'w'
        >>> n = 2
        >>> write_to(fpath, to_write, aslines, verbose, onlyifdiff, mode, n)
        >>> read_ = ut.read_from(fpath)
        >>> print('read_    = ' + read_)
        >>> print('to_write = ' + to_write)
        >>> assert read_ == to_write
    """
    if onlyifdiff:
        import utool as ut
        if ut.hashstr(read_from(fpath)) == ut.hashstr(to_write):
            print('[util_io] * no difference')
            return
    verbose = _rectify_verb_write(verbose)
    if verbose:
        # n = None if verbose > 1 else 2
        # print('[util_io] * Writing to text file: %r ' % util_path.tail(fpath, n=n))
        print('[util_io] * Writing to text file: {}'.format(fpath))

    backup = False and exists(fpath)
    if backup:
        util_path.copy(fpath, fpath + '.backup')

    if not isinstance(fpath, six.string_types):
        # Assuming a file object with a name attribute
        # Should just read from the file
        fpath = fpath.name

    with open(fpath, mode) as file_:
        if aslines:
            file_.writelines(to_write)
        else:
            # Ensure python2 writes in bytes
            if six.PY2:
                if isinstance(to_write, unicode):  # NOQA
                    to_write = to_write.encode('utf8')
            try:
                file_.write(to_write)
            except UnicodeEncodeError as ex:
                start = max(ex.args[2] - 10, 0)
                end = ex.args[3] + 10
                context = to_write[start:end]
                print(repr(context))
                print(context)
                from utool import util_dbg
                util_dbg.printex(ex, keys=[(type, 'to_write')])
                file_.close()
                if backup:
                    # restore
                    util_path.copy(fpath + '.backup', fpath)
                # import utool
                # utool.embed()
                raise