简单的Unicode字符串例子 uniFile.py

来源:互联网 发布:foxmail mac 编辑:程序博客网 时间:2024/05/21 11:07

这个简单的例子中,把一个Unicode字符串写入到磁盘文件,然后再把它读出并显示出来。写入和读出都用UTF-8编码


#/usr/bin/env python'''An example of reading and writing Unicode strings:Writesa 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!

0 0
原创粉丝点击