Problems with encoding

P

Paulo da Silva

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 !

Thanks for any help.
 
A

Alex Martelli

Paulo da Silva said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,206
Messages
2,571,069
Members
47,677
Latest member
MoisesKoeh

Latest Threads

Top