Problems with character encoding when piping output from a python script to a file

Suppose my_unicode_string is a Python unicode string. If you get an error when you do the following:

file_handle.write(my_unicode_string)

and the error is:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in position 9: ordinal not in range(128)

To get rid of the error, you need to explicitly specify encoding:

file_handle.write(my_unicode_string.encode('utf-8'))
Advertisements
This entry was posted in Programming, Python. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s