Python Base64 提供了好几种方法例如:
encode,
decode,
encodestring,
decodestring,
b64encode,
b64decode,
standard_b64encode
standard_b64decode
urlsafe_b64decode,
urlsafe_b64encode。
encode, decode
用来转码和 解码文件的,也可以对StringIO里的数据做编解码#读取文件进行编码 inputRead = open('/Users/Mr_Chen/Desktop/test.jpeg','rb') outputWrit = open('/Users/Mr_Chen/Desktop/testEncode.txt','wb') #编码文件 base64Test = base64.encode(inputRead,outputWrit) #读取文件后进行解码 inputRead = open('/Users/Mr_Chen/Desktop/testEncode.txt','rb') outputWrit = open('/Users/Mr_Chen/Desktop/testDecode.jpeg','wb') #解码文件 base64Test2 = base64.decode(inputRead,outputWrit)
encodestring, decodestring,
对字符串进行转码,解码import base64 str1 = 'This is Test String' #对字符串进行转码 enTest = base64.encodestring(str1) print '转码后:',enTest #对字符串进行解码 deTest = base64.decodestring(enTest) print '解码后:',deTest
b64encode,b64decode,
(base64 模块提供了 b16encode,b16decode,b32encode,b32decode)
用来编码和解码字符串,并且有一个替换符号字符的功能。当base64编码后的字符除 了英文字母和数字外还有三个字符 + / =,用提替换到 +/= 这些字符# -*- coding:utf-8 -*- import base64 #读取文件进行base16转码 inputRead = open('/Users/Mr_Chen/Desktop/test.txt','rb') base16Test = base64.b16encode(inputRead.read()) inputRead.close() print 'base16 Encode:',base16Test #进行base16解码 base16Test2 = base64.b16decode(base16Test) print 'base16 Decode:',base16Test2 #读取文件进行base32转码 inputRead2 = open('/Users/Mr_Chen/Desktop/test.txt','rb') base32Test = base64.b32encode(inputRead2.read()) inputRead2.close() print 'base32 Encode:',base32Test #进行base32转码 base32Test2 = base64.b32decode(base32Test) print 'base32 Decode:',base32Test2 #读取文件进行base64转码 inputRead3 = open('/Users/Mr_Chen/Desktop/test64.txt','rb') base64Test = base64.b64encode(inputRead3.read()) inputRead3.close() print 'base64 Encode:',base64Test #进行base64解码 base64Test2 = base64.b64decode(base64Test) print 'base64 Decode:',base64Test2
standard_b64encode,standard_b64decode
进行标准的base64,同样可以进行string ,文件的转码,解码
使用效果和encodestring 相同# -*- coding:utf-8 -*- import base64 text = 'This is Test String!' #进行转码 baseStand = base64.standard_b64encode(text) print 'baseStand:',baseStand #进行解码 basee = base64.encodestring(text) print 'baseEncodeString:',basee
urlsafe_b64decode,urlsafe_b64encode
主要进行对url 的安全转码# -*- coding:utf-8 -*- import base64 text = "http://www.baidu.com" #baseurl Encode 转码 baseUrl = base64.urlsafe_b64encode(text) print "baseUrlEncode:" ,baseUrl #baseurl Encode 解码 baseUrl2 = base64.urlsafe_b64decode(baseUrl) print "baseUrlDecode:" ,baseUrl2
版权声明:本文为博主原创文章,未经博主允许不得转载。