How to write a unicode object into a file in Python? -


i try write "string" file , following error message:

unicodeencodeerror: 'ascii' codec can't encode character u'\xcd' in position 6: ordinal not in range(128) 

i tried following methods:

print >>f, txt print >>f, txt.decode('utf-8') print >>f, txt.encode('utf-8') 

none of them work. have same error message.

what idea behind encoding , decoding? if have unicode object can write file directly or need transform string?

how can find out codding used? how can know if utf-8 or ascii or else?

added

i think have managed save string file. print >>f, txt print >>f, txt.decode('utf-8') did not work print >>f, txt.encode('utf-8') works. no error message , see chinese characters in file.

i posted another answer addresses issue. key quote:

for overview of difference, read one of joel's articles, gist bytes are, well, bytes (groups of 8 bits without further meaning attached), whereas characters things make strings of text. encoding turns characters bytes, , decoding turns bytes characters.

in python 2, unicode objects character strings. regular str objects can either character strings or byte strings. (pro tip: use python 3, makes keeping track lot easier.)

you should passing character strings (not byte strings) print, need sure character strings can encoded codec (such ascii or utf-8) associated destination file object f. part of output process, python encodes string you. if string contains characters cannot encoded file object's codec, errors 1 you're seeing.

without knowing in txt object can't more specific.


Comments

Popular posts from this blog

javascript - How to get current YouTube IDs via iMacros? -

c# - Maintaining a program folder in program files out of date? -

emulation - Android map show my location didn't work -