Writer text to file with utf-8 encoding.

    Usage::

        >>> from angora.dataIO import textfile
        or
        >>> from angora.dataIO import *
        >>> textfile.write("hello world!", "test.txt")
545387
def write(text, path):
    
    with open(path, "wb") as f:
        f.write(text.encode("utf-8"))
779831
def _set_file_encoding_utf8(filename):
    """"""
    with open(filename, 'r+') as f:
        content = f.read()
        f.seek(0, 0)
        f.write("# -*- coding: utf-8 -*-\n" + content)
548566
def to_utf8(path, output_path=None):
    
    if output_path is None:
        basename, ext = os.path.splitext(path)
        output_path = basename + "-UTF8Encode" + ext
    
    text = smartread(path)
    write(text, output_path)
1139931
def write_file(file_path, txt, **kws):
    
    if not os.path.exists(file_path):
        upDir = os.path.dirname(file_path)
        if not os.path.isdir(upDir):
            os.makedirs(upDir)

    kw = {"mode":"w", "encoding":"utf-8"}
    if kws:
        for k,v in kws.items():
            kw[k] = v
    with open(file_path, **kw) as afile:
        afile.write(txt)
1180294
def write(self, text):
        '''  '''
        # Output is converted to bytes with Windows-style line endings.
        if sys.version_info[0] == 2:
            text_bytes = str(text.upper() + '\r\n').encode('utf-8')
        else:
            text_bytes = bytes(text.upper() + '\r\n', 'utf-8')
        self.ser.write(text_bytes)
1284573
def writeFile(filename, data):
		
		with open(filename, 'wb') as f:
			f.write(data.encode('utf-8'))
160112
def text(self,txt):
        
        if not txt:
            return
        try:
            txt = txt.decode('utf-8')
        except:
            try:
                txt = txt.decode('utf-16')
            except:
                pass

        self.extra_chars = 0
        
        def encode_char(char):  
            """ 
            Encodes a single utf-8 character into a sequence of 
            esc-pos code page change instructions and character declarations 
            """ 
            char_utf8 = char.encode('utf-8')
            encoded  = ''
            encoding = self.encoding # we reuse the last encoding to prevent code page switches at every character
            encodings = {
                    # TODO use ordering to prevent useless switches
                    # TODO Support other encodings not natively supported by python ( Thai, Khazakh, Kanjis )
                    'cp437': TXT_ENC_PC437,
                    'cp850': TXT_ENC_PC850,
                    'cp852': TXT_ENC_PC852,
                    'cp857': TXT_ENC_PC857,
                    'cp858': TXT_ENC_PC858,
                    'cp860': TXT_ENC_PC860,
                    'cp863': TXT_ENC_PC863,
                    'cp865': TXT_ENC_PC865,
                    'cp866': TXT_ENC_PC866,
                    'cp862': TXT_ENC_PC862,
                    'cp720': TXT_ENC_PC720,
                    'cp936': TXT_ENC_PC936,
                    'iso8859_2': TXT_ENC_8859_2,
                    'iso8859_7': TXT_ENC_8859_7,
                    'iso8859_9': TXT_ENC_8859_9,
                    'cp1254'   : TXT_ENC_WPC1254,
                    'cp1255'   : TXT_ENC_WPC1255,
                    'cp1256'   : TXT_ENC_WPC1256,
                    'cp1257'   : TXT_ENC_WPC1257,
                    'cp1258'   : TXT_ENC_WPC1258,
                    'katakana' : TXT_ENC_KATAKANA,
            }
            remaining = copy.copy(encodings)

            if not encoding :
                encoding = 'cp437'

            while True: # Trying all encoding until one succeeds
                try:
                    if encoding == 'katakana': # Japanese characters
                        if jcconv:
                            # try to convert japanese text to a half-katakanas 
                            kata = jcconv.kata2half(jcconv.hira2kata(char_utf8))
                            if kata != char_utf8:
                                self.extra_chars += len(kata.decode('utf-8')) - 1
                                # the conversion may result in multiple characters
                                return encode_str(kata.decode('utf-8')) 
                        else:
                             kata = char_utf8
                        
                        if kata in TXT_ENC_KATAKANA_MAP:
                            encoded = TXT_ENC_KATAKANA_MAP[kata]
                            break
                        else: 
                            raise ValueError()
                    else:
                        encoded = char.encode(encoding)
                        break

                except ValueError: #the encoding failed, select another one and retry
                    if encoding in remaining:
                        del remaining[encoding]
                    if len(remaining) >= 1:
                        encoding = remaining.items()[0][0]
                    else:
                        encoding = 'cp437'
                        encoded  = '\xb1'    # could not encode, output error character
                        break;

            if encoding != self.encoding:
                # if the encoding changed, remember it and prefix the character with
                # the esc-pos encoding change sequence
                self.encoding = encoding
                encoded = encodings[encoding] + encoded

            return encoded
        
        def encode_str(txt):
            buffer = ''
            for c in txt:
                buffer += encode_char(c)
            return buffer

        txt = encode_str(txt)

        # if the utf-8 -> codepage conversion inserted extra characters, 
        # remove double spaces to try to restore the original string length
        # and prevent printing alignment issues
        while self.extra_chars > 0: 
            dspace = txt.find('  ')
            if dspace > 0:
                txt = txt[:dspace] + txt[dspace+1:]
                self.extra_chars -= 1
            else:
                break

        self._raw(txt)
45911
def write_var_str(self, value, encoding: str = 'utf-8'):
        
        if isinstance(value, str):
            value = value.encode(encoding)
        self.write_var_int(len(value))
        self.write_bytes(value)
1297885
def utf8(value, encoding=None):
    
    if isinstance(value, _UTF8_TYPES):
        return value
    if not isinstance(value, text_type):
        raise TypeError(
            "Expected bytes, unicode, or None; got %r" % type(value)
        )

    if encoding is not None:
        return value.encode(encoding)

    try:
        return value.encode('utf-8')
    except:
        return value.encode('gbk')
465120
def load(self, encoding='utf8', encoding_errors='ignore'):  # pylint: disable=arguments-differ
        
        if isinstance(self.codec, codec.NoCodec) and \
           self.fs.load_text != FileSystem.load_text:
            stream = self.fs.load_text(encoding, encoding_errors)
        else:
            stream = self.fs.load()
            stream = self.codec.decompress(stream)
            stream = TextIOWrapper(stream, encoding, encoding_errors)
        return stream
802413
def astext(data):
    
    if isinstance(data, str):
        return data
    elif isinstance(data, text_type):
        return data.encode("utf-8", "ignore")
    elif isinstance(data, binary_type):
        return data.decode("utf-8", "ignore")
    raise TypeError('{!r} not a string'.format(data))
280529
def write_tsv(output_stream, *tup, **kwargs):
    
    encoding = kwargs.get('encoding') or 'utf-8'
    value = '\t'.join([s for s in tup]) + '\n'
    output_stream.write(value.encode(encoding))
1069099
def Write(self, string):
    
    try:
      # Note that encode() will first convert string into a Unicode string
      # if necessary.
      encoded_string = codecs.encode(string, self._encoding, self._errors)
    except UnicodeEncodeError:
      if self._errors == 'strict':
        logger.error(
            'Unable to properly write output due to encoding error. '
            'Switching to error tolerant encoding which can result in '
            'non Basic Latin (C0) characters to be replaced with "?" or '
            '"\\ufffd".')
        self._errors = 'replace'

      encoded_string = codecs.encode(string, self._encoding, self._errors)

    self._file_object.write(encoded_string)
110389
def write(self, data):
        
        if pyver == 2:
             if isinstance(data, unicode):
                data = data.encode("utf-8")
             else:
                data = str(data)
        else:
             if not isinstance(data, bytes): 
                data=str(data).encode("utf-8")   

        written = libcrypto.BIO_write(self.bio, data, len(data))
        if written == -2:
            raise NotImplementedError("Function not supported by this BIO")
        if written < len(data):
            raise IOError("Not all data were successfully written")
20014
def write(self, location, text, encoding):
        
        location = os.path.expanduser(location)

        with codecs.open(location, 'w', encoding) as f:
            f.write(text)
1100635
def write_longstr(self, s):
        
        self._flushbits()
        if isinstance(s, text_t):
            s = s.encode('utf-8')
        self.write_long(len(s))
        self.out.write(s)
938604
def write_text(self, data, encoding=None, errors=None):
        
        if not isinstance(data, six.text_type):
            raise TypeError(
                'data must be %s, not %s' %
                (six.text_type.__class__.__name__, data.__class__.__name__))
        with self.open(mode='w', encoding=encoding, errors=errors) as f:
            return f.write(data)