There are many useful modules in the Python programming language for us to get some help in practical applications. For example, the Python base64 module introduced today is an important module. Here we will give a detailed introduction to the basic concepts of this module.
The Python base64 module is used for base64 encoding and decoding. This encoding method is very common in email. It can encode binary data that cannot be displayed as text information to be displayed. The encoded text size increases by 1/3.
Simplest encryption/Decryption instance
- import base64
- str1 = 'djhui'
- str2 = base64.b64encode(str1)
- str3 = base64.b64decode(str2)
The Python base64 module only uses eight methods: encode, decode, encodestring, decodestring, b64encode, b64decode, urlsafe_b64decode, and urlsafe_b64encode. The eight of them can be divided into four groups: encode and decode, which are used to encode and decode files. They can also perform encoding and decoding on the data in StringIO; encodestring and decodestring, this function is used to encode and decode strings. b64encode and b64decode are used to encode and decode strings and replace symbol characters.
This function is like this: the base64 encoded characters include three letters +/=, here, the value = is only used to encode the number of characters with four integers, while the value + and/must be replaced in some cases. b64encode and b64decode provide this function. When + and/need to be replaced, the most common is the base64 encoding of the url. Urlsafe_b64encode and urlsafe_b64decode are used to encode and encode the url in base64. in fact, they are also called by the previous functions.
The following is an example of the Python base64 module:
- #-*-Encoding: gb2312 -*-
- Import base64
- Import StringIO
- A = "this is a test"
- B = base64.encodestring (a) # encode the string
- Print B
- Print base64.decodestring (B) # decodes a string
- C = StringIO. StringIO ()
- C. write ()
- D = StringIO. StringIO ()
- E = StringIO. StringIO ()
- C. seek (0)
- Base64.encode (c, d) # encode the data in StringIO
- Print d. getvalue ()
- D. seek (0)
- Base64.decode (d, e) # decode the data in StringIO
- Print e. getvalue ()
- A = "this is a + test"
- B = base64.urlsafe _ b64encode (a) # encode the url string
- Print B
- Print base64.urlsafe _ b64decode (B)
The above encode function and decode function parameters can also be file objects, which is like this:
- f1 = open('aaa.txt', 'r')
- f2 = open('bbb.txt', 'w')
- base64.encode(f1, f2)
- f1.close()
- f2.close()
The above is the concept of the Python base64 module.