Python 3 二进制文件的base64编码

Python 3 and base64 encoding of a binary file

我是 Python 的新手,我确实有一个问题困扰着我。

我使用以下代码获取我的 zip 文件的 base64 字符串表示形式。

with open( "C:\Users\Mario\Downloads\exportTest1.zip",'rb' ) as file:
    zipContents = file.read()
    encodedZip = base64.encodestring(zipContents)

现在,如果我输出它包含在 b'' 表示中的字符串。这对我来说是没有必要的,我想避免它。它还每 76 个字符添加一个换行符,这是另一个问题。有没有办法获取二进制内容并在没有换行符以及尾随和前导 b'' 的情况下表示它?

只是为了比较,如果我在 PowerShell 中执行以下操作:

$fileName = "C:\Users\Mario\Downloads\exportTest1.zip"
$fileContentBytes = [System.IO.File]::ReadAllBytes($fileName)
$fileContentEncoded = [System.Convert]::ToBase64String($fileContentBytes) 

我确实得到了我正在寻找的确切字符串,每 76 个字符都没有 b'' 和 \n。

来自base64 package doc:

base64.encodestring:

"Encode the bytes-like object s, which can contain arbitrary binary data, and return bytes containing the base64-encoded data, with newlines (b"\n") inserted after every 76 bytes of output, and ensuring that there is a trailing newline, as per RFC 2045 (MIME)."

您想使用

base64.b64encode:

"Encode the bytes-like object s using Base64 and return the encoded bytes."

示例:

import base64

with open("test.zip", "rb") as f:
    encodedZip = base64.b64encode(f.read())
    print(encodedZip.decode())

decode() 将二进制字符串转换为文本。

使用 b64encode 编码不带换行符,然后使用 .decode('ascii') 解码生成的二进制字符串以获得正常字符串。

encodedZip = base64.b64encode(zipContents).decode('ascii')