python编码案例_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。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值