本文地址:http://blog.csdn.net/morewindows/article/details/11922473转载请标明出处,谢谢。
欢迎关注微博:http://weibo.com/MoreWindows
本系列一共四篇:
1. 《Base64系列第一篇 Base64介绍》
2. 《Base64系列第二篇 python中使用Base64编码解码》
3. 《Base64系列第三篇 C/C++中使用Base64编码解码(使用boost库)》
4. 《Base64系列第四篇 C/C++中使用Base64编码解码(从chromium库中抽取)》
本篇《Base64系列第二篇 python中使用Base64编码解码》将介绍如何使用python来完成Base64的编码解码
在python中使用base64编码和解码都是非常方便的,在import base64模块后直接使用encodestring()和decodestring()就可以了,先使用基于URL的改进Base64编码的同样方便,python已经提供了urlsafe_b64encode()urlsafe_b64decode()供使用。
下面给出python的示范代码:
# http://blog.csdn.net/morewindows/article/details/11922473
# By MoreWindows ( http://blog.csdn.net/MoreWindows )
# more info please visit http://www.python.org/doc//current/library/base64.html
import base64
text = "MoreWindows - http://blog.csdn.net/morewindows?viewmode=contents ~!@#$%"
# encodestring(string) and decodestring(string)
print "------------------------------------"
print "origin text: "
print text
base64_text = base64.encodestring(text)
print "encode: "
print base64_text
print "decode: "
print base64.decodestring(base64_text)
print "------------------------------------"
# urlsafe_b64encode(string) and urlsafe_b64decode(string)
print "------------------------------------"
print "origin text: "
print text
urlsafe_base64_text = base64.urlsafe_b64encode(text)
print "url safe encode: "
print urlsafe_base64_text
print "url safe decode: "
print base64.urlsafe_b64decode(urlsafe_base64_text)
print "------------------------------------"
运行结果如下:
要对文件操作该怎么办了,python也提供了相应的接口,示范代码如下:
# http://blog.csdn.net/morewindows/article/details/11922473
# By MoreWindows ( http://blog.csdn.net/MoreWindows )
# more info please visit http://www.python.org/doc//current/library/base64.html
# base64.encode(file1, file2)
f1 = open('aaa.txt', 'r')
f2 = open('bbb.txt', 'w')
base64.encode(f1, f2)
f1.close()
2.close()
下面二篇《Base64系列第三篇 C/C++中使用Base64编码解码(使用boost库)》和《Base64系列第四篇 C/C++中使用Base64编码解码(从chromium库中抽取)》将介绍在C/C++中使用Base64编码和解码,欢迎继续浏览。
本文地址:http://blog.csdn.net/morewindows/article/details/11922473转载请标明出处,谢谢。
欢迎关注微博:http://weibo.com/MoreWindows