Python: Base64文件編碼、解碼

base64.py 模型提供了將二進制數據編碼爲可印刷的 ASCII 字符和將這些編碼後的數據返回到二進制數據的方法。

一、方法

  • b64encode(saltchars=None)

1. 使用 Base64 編碼類字節對象(bytes-like object),並返回編碼字節;

bytes-like object

An object that supports the Buffer Protocol and can export a C-contiguous buffer. This includes all bytesbytearray, and array.array objects, as well as many common memoryview objects. Bytes-like objects can be used for various operations that work with binary data; these include compression, saving to a binary file, and sending over a socket.

Some operations need the binary data to be mutable. The documentation often refers to these as “read-write bytes-like objects”. Example mutable buffer objects include bytearray and a memoryview of a bytearray. Other operations require the binary data to be stored in immutable objects (“read-only bytes-like objects”); examples of these include bytes and a memoryview of a bytes object.

2. altchars 參數必須有至少兩個類字節對象(bytes-like object),用來替換 '+' '/' 等符號,默認 None

  • b64decode(saltchars=Nonevalidate=False)

1. 解碼使用 Base64 編碼的類字節對象(bytes-like object)或者 ASCII 字符串,並返回解碼字節;

2. 同上;

3. 如果 validateFalse (默認值),則在填充檢查之前,將丟棄既不在普通的 base-64 字母表中也不在備用字母表中的字符。

  • standard_b64encode(s)

編碼將採用標準的 Base64 字母表。

  • standard_b64decode(s)

解碼將採用標準的 Base64 字母表。

  • urlsafe_b64encode(s)

標準的 Base64 字母表使用 '/' 替換 '+' '_' ,該方法使用 URL-safefilesystem-safe 字母表,使用 '-' 替換 '+' '_' 。最終結果仍然保留 '='

  • urlsafe_b64decode(s)

  • encode(inputoutput)

input 文件編碼,並將 base64 編碼的結果寫入到 output 文件中。是通過 input.read() 讀取。

注意: inputoutput 必須時文件對象;output 中每 76 個字節,encode() 方法都會插入一個換行符( b'\n' ),從而確保 output 都是以新的一行結束。

  • decode(inputoutput)

input 文件解碼,並將解碼的結果寫入到 output 文件中。是通過 input.readline() 讀取。

二、舉例

>>> import base64
>>> encoded = base64.b64encode(b'data to be encoded')
>>> encoded
b'ZGF0YSB0byBiZSBlbmNvZGVk'
>>> data = base64.b64decode(encoded)
>>> data
b'data to be encoded'

更多信息請看官方文檔:https://docs.python.org/3.6/library/base64.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章