这个简单的例子中,把一个Unicode字符串写入到磁盘文件,然后再把它读出并显示出来。写入和读出都用UTF-8编码
#/usr/bin/env python
'''
An example of reading and writing Unicode strings:Writes
a Unicode string to a file in utf-8 and reads it back in.
'''
CODEC = 'utf-8'
FILE = 'unicode.txt'
hello_out = u"Hello world\n"
bytes_out = hello_out.encode(CODEC)
f = open(FILE,"w")
f.write(bytes_out)
f.close()
f = open(FILE,"r")
bytes_in = f.read()
f.close()
hello_in = bytes_in.decode(CODEC)
print hello_in,
运行程序得到如下输出
$unicode_example.py
Hello World
创建一个叫unicode.txt的文件
$cat unicode.txt
Hello World!