While working with unicode characters in python, you have to use special encoding and decoding functions.
Here is a sample code for writing unicode characters to a file:
import io try: to_unicode = unicode except NameError: to_unicode = str data=u'Δ, Й, ק, م, ๗, あ, 叶, 葉, and 말.' with io.open('data.txt', 'w', encoding='utf8') as f: f.write(to_unicode(data))
In this code, first we define encoding of the file while creating the file object.
After creating file object we encode the string in unicode, so io object will write it in correct format.
try-except block in this code is added to make the code work both on python 2 and 3.
I hope you found this snippet useful. Don’t forget to subscribe for more.