Archive

Posts Tagged ‘read unicode text from file’

Writing non-ASCII text to file

December 2, 2012 2 comments

Problem
You download the source of an HTML page in a string and you want to save it in a file. However, you get some UnicodeDecodeError :(

Solution

foo = u'Δ, Й, ק, ‎ م, ๗, あ, 叶, 葉, and 말.'
f = open('test', 'w')
f.write(foo.encode('utf8'))
f.close()

Here is how to read it back:

f = open('test', 'r')
print f.read().decode('utf8')

This tip is from here.

Design a site like this with WordPress.com
Get started