我是 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 包文档: https://docs.python.org/3.5/library/base64.html
base64.encodestring: https://docs.python.org/3.5/library/base64.html#base64.encodestring
“对可包含任意二进制数据的类字节对象s进行编码,并返回bytes
包含 base64 编码的数据,带有换行符 (b"\n"
) 在每 76 个字节的输出之后插入,并确保有一个尾随换行符,按照 RFC 2045 (MIME)。”
你想使用
base64.b64encode: https://docs.python.org/3.5/library/base64.html#base64.b64encode
“使用 Base64 对类似字节的对象进行编码并返回编码后的对象bytes
."
Example:
import base64
with open("test.zip", "rb") as f:
encodedZip = base64.b64encode(f.read())
print(encodedZip.decode())
The decode()
会将二进制字符串转换为文本。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)