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

发布了25 篇原创文章 · 获赞 37 · 访问量 2944

猜你喜欢

转载自blog.csdn.net/qq_41297934/article/details/103306158