how to write unicode to a txt file?

F

Frank Potter

I want to change an srt file to unicode format so mpalyer can display
Chinese subtitles properly.
I did it like this:

txt=open('dmd-guardian-cd1.srt').read()
txt=unicode(txt,'gb18030')
open('dmd-guardian-cd1.srt','w').write(txt)

But it seems that python can't directly write unicode to a file,
I got and error at the 3rd line:
UnicodeEncodeError: 'ascii' codec can't encode characters in position
85-96: ordinal not in range(128)

How to save the unicode string to the file, please?
Thanks!
 
P

Peter Otten

Frank said:
I want to change an srt file to unicode format so mpalyer can display
Chinese subtitles properly.
I did it like this:

txt=open('dmd-guardian-cd1.srt').read()
txt=unicode(txt,'gb18030')
open('dmd-guardian-cd1.srt','w').write(txt)

But it seems that python can't directly write unicode to a file,
I got and error at the 3rd line:
UnicodeEncodeError: 'ascii' codec can't encode characters in position
85-96: ordinal not in range(128)

How to save the unicode string to the file, please?
Thanks!

You have to tell Python what encoding to use (i. e how to translate the
codepoints into bytes):
u'\xe4hnlicher als gew\xf6hnlich \xfcblich'

You would perhaps use 'gb18030' instead of 'utf8'.

Peter
 
F

Facundo Batista

Frank said:
But it seems that python can't directly write unicode to a file,

You need to use the method open from module codecs:

So, then, from command line:

facundo@expiron:~$ file pru_uni.txt
pru_uni.txt: UTF-8 Unicode text

:)

Regards,
 

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

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top