python编码,三个编码实例

1、字符串编码设置

data = u'你好'
utf8 = data.encode('utf-8')

 2、管道编码设置

import locale
import sys

###设置输出管道编码###
text = u'pi:π'
locale.setlocale(locale.LC_ALL, '')   #恢复系统默认
lang, encoding = locale.getdefaultlocale()  #获取系统默认设置(或用户设置)过的lang、encoding
print 'Locale lang: ', lang
print 'Locale encoding: ', encoding
sys.stdout = codecs.getwriter(encoding)(sys.stdout)  #将输出管道的编码设置为刚刚获取到的默认encoding
print 'Print with wrapped stdout: ', text

###设置输入管道编码###
locale.setlocale(locale.LC_ALL, '')
lang, encoding = locale.getdefaultlocale()
sys.stdin = codecs.getreader(encoding)(sys.stdin)  #注意这里是getreader()
print 'From stdin:'
print repr(sys.stdin.read())

 3、文件、字符串写入读取编码转换设置

# -*- coding:utf-8 -*-
import sys
import codecs

reload(sys)
sys.setdefaultencoding('utf-8')   
data = u'你好'
utf8 = data.encode('utf-8')
print utf8
with codecs.open('file1.txt', 'w', 'utf-8') as f:
	encoded_file = codecs.EncodedFile(f, data_encoding='utf-8', file_encoding='utf-8')
	encoded_file.write(utf8)
with codecs.open('file1.txt', 'r', 'utf-8') as f:
	encoded_file = codecs.EncodedFile(f, data_encoding='gbk', file_encoding='utf-8')
	print encoded_file.read()

  注意:codecs.EncodedFile(file, data_encoding, file_encoding=None, errors='strict') 

  该函数返回一个StreamRecoder对象,主要提供一个透明转换两种编码的机制。当数据将要写文件时,要先经过data_encoding进行解码,接着进行file_encoding编码,最后把数据写入到文件。当要从文件读取数据时,先经过file_encoding进行解码,接着进行data_encoding编码,最后把数据交给使用者。

  如果file_encoding不存在,默认是使用data_encoding来替换。

  errors是错误的处理方式,默认是strict处理方式,如果不能处理会抛出异常ValueError

原文地址:https://www.cnblogs.com/yxpblog/p/5260038.html