二进制文件的 Python 3 和 base64 编码

标签 python python-3.x base64 binaries

我是 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) 

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

最佳答案

来自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() 会将二进制字符串转换为文本。

关于二进制文件的 Python 3 和 base64 编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37944806/

相关文章:

base64 - RFC 3548 和 RFC 4648 之间的差异

python - 在 Django 1.7 中序列化类方法

python-3.x - 如何使用 Linux alpine 3.13 在 Docker 镜像上安装 hdf5

python - 从 dict 制作 Dataframe

ruby - 为什么 Ruby base64 编码字符串与所有其他 base64 编码字符串不同?

java - 在内联电子邮件正文中发送 Base64 编码图像

python - 在 python 中,为什么使用日志而不是打印?

python - Selenium 无法使用 python 抓取 Shopee 电子商务网站

python - 在 Python 中内存整个 block

python - 为什么在存储 fetchone() 值时显示 TypeError?