样例# -*- coding: utf-8 -*-
s = u'中文'
print s 在控制台中分别运行 python test.py 和 python test.py > 1.txt
你会发现后者会报错,原因是打印控制台时Python会自动转换编码到sys.stdout.encoding, 而输出到文件时Python不会自动在write调用中进行内部字符转换。这个问题在PrintFails中有较详细的说明。
UTF-8编码格式
保存utf-8格式的文件
import codecs
fileObj = codecs.open( "someFile", "r", "utf-8" )
u = fileObj.read() # Returns a Unicode string from the UTF-8 bytes in the file
去掉BOMimport codecs
if s.beginswith( codecs.BOM_UTF8 ):
# The byte string s begins with the BOM: Do something.
# For example, decode the string as UTF-8
if u[0] == unicode( codecs.BOM_UTF8, "utf8" ):
# The unicode string begins with the BOM: Do something.
# For example, remove the character.
# Strip the BOM from the beginning of the Unicode string, if it exists
u.lstrip( unicode( codecs.BOM_UTF8, "utf8" ) ) 源码文件的编码
关于Python对代码文件的编码处理,PEP0263 讲的很清楚,现摘录如下
python缺省认为文件为ASCII编码。
可在代码头一行或二行加入声明文件编码申明,通知python该文件的编码格式,如
# -*- coding: utf-8 –*- # 注意使用的编辑器,确保文件保存时使用了该编码格式