转载自:http://blog.csdn.net/zhaoweikid/archive/2007/05/31/1633470.aspx 

这篇文章转自我在百度的blog: http://hi.baidu.com/python23/
    base64模块是用来作base64编码解码的。这种编码方式在电子邮件中是很常见的。
它可以把不能作为文本显示的二进制数据编码为可显示的文本信息。编码后的文本大小会增大1/3。

    闲话不说了,base64模块真正用的上的方法只有8个,分别是encode, decode, encodestring, decodestring, b64encode,b64decode, urlsafe_b64decode,urlsafe_b64encode。他们8个可以两两分为4组,encode,decode一组,专门用来编码和 解码文件的,也可以对StringIO里的数据做编解码;encodestring,decodestring一组,专门用来编码和解码字符串; b64encode和b64decode一组,用来编码和解码字符串,并且有一个替换符号字符的功能。这个功能是这样的:因为base64编码后的字符除 了英文字母和数字外还有三个字符 + / =, 其中=只是为了补全编码后的字符数为4的整数,而+和/在一些情况下需要被替换的,b64encode和b64decode正是提供了这样的功能。至于什 么情况下+和/需要被替换,最常见的就是对url进行base64编码的时候。urlsafe_b64encode和urlsafe_b64decode 一组,这个就是用来专门对url进行base64编解码的,实际上也是调用的前一组函数。
下面看看例子:

python模块之base64#-*- encoding:gb2312 -*-
python模块之base64
import base64
python模块之base64
import StringIO
python模块之base64
python模块之base64
= "this is a test"
python模块之base64
= base64.encodestring(a) # 对字符串编码
python模块之base64
print b
python模块之base64
print base64.decodestring(b) # 对字符串解码
python模块之base64

python模块之base64
= StringIO.StringIO()
python模块之base64c.write(a)
python模块之base64
= StringIO.StringIO()
python模块之base64
= StringIO.StringIO()
python模块之base64c.seek(0)
python模块之base64base64.encode(c, d) 
# 对StringIO内的数据进行编码
python模块之base64
print d.getvalue()
python模块之base64d.seek(0)
python模块之base64base64.decode(d, e) 
# 对StringIO内的数据进行解码
python模块之base64
print e.getvalue()
python模块之base64
python模块之base64
= "this is a +test"
python模块之base64
= base64.urlsafe_b64encode(a) # 进行url的字符串编码
python模块之base64
print b
python模块之base64
print base64.urlsafe_b64decode(b)
python模块之base64


上面的encode函数和decode函数的参数其实还可以是文件对象的,那的象这样:

python模块之base64f1 = open('aaa.txt''r')
python模块之base64f2 
= open('bbb.txt''w')
python模块之base64
python模块之base64base64.encode(f1, f2)
python模块之base64
python模块之base64f1.close()
python模块之base64f2.close()

相关文章:

  • 2021-12-26
  • 2021-12-25
  • 2022-12-23
  • 2021-11-28
  • 2021-09-10
  • 2021-12-29
  • 2021-11-16
  • 2022-02-02
猜你喜欢
  • 2022-12-23
  • 2022-02-16
  • 2021-09-13
  • 2021-09-03
  • 2021-06-01
  • 2021-11-29
相关资源
相似解决方案