how to print the GREEK CAPITAL LETTER delta under utf-8 encoding

Ragnar Ouchterlony ragnar at lysator.liu.se
Tue May 29 14:16:52 EDT 2007


tis 2007-05-29 klockan 09:05 +0200 skrev "Martin v. Lo"wis":
> Yes, when writing to a file, you need to define an encoding, e.g.
> 
> self.file.write(data.encode("utf-8"))
> 
> You can use codecs.open() instead of open(),
> so that you can just use self.file.write(data)

If I for some reason can't open the object myself or needs encoding on
other file-like objects, I think the following wrapper function is of
use (it essentially does what codecs.open() does but takes a file-object
instead of a filename):

def filewrapper(f, encoding=None, errors='strict'):
    if encoding is None:
        return f

    info = codecs.lookup(encoding)
    srw = codecs.StreamReaderWriter(f, info.streamreader,
                                    info.streamwriter, errors)
    # Add attributes to simplify introspection
    srw.encoding = encoding
    return srw

I find this especially useful for changing how stdout and friends does
it's encoding, e.g:

>>> sys.stdout = filewrapper(sys.stdout, 'utf-8')
>>> print u"åäö \N{GREEK CAPITAL LETTER DELTA}"

Useful if you don't want to append .encode() to everything you print out
that potentially can contain non-ascii letters.

/Ragnar




More information about the Python-list mailing list