Problems with encoding

Alex Martelli aleaxit at yahoo.com
Sat Sep 18 03:49:08 EDT 2004


Paulo da Silva <psXdaXsilva at esotericaX.ptX> wrote:

> Hi.
> 
> I am using unicode encode method to write some
> accented chars to files (%s). Do I need to use
> the method "encode" always? Isn't there a general
> way to declare the encoding for the whole program?
> I have tried sys.setdefaultencoding but there was
> no such method !

sys.setdefaultencoding gets removed right after the startup phase
(execution of site.py &c), because it's not meant to be called anymore
after that.  Nothing stops you from bypassing Python's helpful attempt
to save you from this error: reload(sys) and call sys.setdefaultencoding
at will, just don't complain as and when something should break in
mysterious ways.  I suggest forgetting this possibility.

More sensibly, you could use codecs.open, instead of the built-in
function open, to open the files you mean to write to.  This way, you
can write Unicode strings to the files directly, and the files will take
care of the encoding.  I suggest you explore this idea, which I believe
is much sounder than "declare encoding for the whole program".


Alex



More information about the Python-list mailing list