python2中向文本中写入unicode编码的中文内容

python2内置库中的open方法只能读写ascii码,如果想写入Unicode字符,需要使用codecs包。
如下例子,用open直接写入会报错,需要用到codecs.open,并且支持设置编码

import codecs

content = u'你好'

print "python2中使用open写入unicode编码的中文:"
try:
    with open('test.csv','w') as fh:
        fh.write(content)
except Exception as e:
    print("程序报错:")
    print(e)
    
print "python2中使用codecs.open写入unicode编码的中文:"  
with codecs.open('test2.csv','w','utf-8') as fh:
    fh.write(content)
    print("写入成功")

python2中向文本中写入unicode编码的中文内容_第1张图片

你可能感兴趣的:(Python学习笔记)