[Tutor] changing unicode to ascii
Peter Otten
__peter__ at web.de
Wed Jan 30 16:33:15 CET 2013
Benjamin Fishbein wrote:
> I was trying to write text to a file and got the following error:
>
> UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in
> position 5495: ordinal not in range(128)
>
> I tried several things I found online, such as:
> text.encode("ascii", "ignore")
> which gave me the same error
Try saving text with
assert type(text) == unicode
with open(filename, "w") as f:
f.write(text.encode("ascii", "ignore"))
If that fails please give the exact traceback. Don't paraphrase, use cut-
and-paste!
If the above works you can preserve your precious data including non-ascii
characters with
import io
assert type(text) == unicode
with io.open(filename, "w") as f:
f.write(text)
More information about the Tutor
mailing list