我是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 100 containing the base64-encoded data, with newlines (101) 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 100."

例子:

import base64

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

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

Python-3.x相关问答推荐

如何在Python Matplotlib中在x轴上放置点

是否有必要使用Threads()中的args显式地将共享变量传递给Python中的线程函数或直接访问它?

向前/向后移动导致移动行的数据不可见

Python webdrivermanager 和 Chrome 115.0 的 URL https://chromedriver.storage.googleapis.com/LATEST_RELEASE_115.0.5790 错误没有此类驱动程序

从另一个云函数调用带有仅允许内部流量标志的云函数时出现问题

pytorch 中 mps 设备的 manual_seed

过滤并获取数据框中条件之间的行

如何向 scikit-learn 函数添加类型提示?

Python BeautifulSoup:在 Select 语句中排除其他标签

是否将dict转换为一个数据帧,每个值都有重复的键?

Pylint 给我最后的新行丢失

if 语句中冒号的语法错误

谁能给我一个 Python 3 中标准输入和标准输出的快速教程?

每次启动 Google Colab 时都必须安装所需的软件包吗?

将 numpy.float64 列表快速转换为 Python 中的浮点数

matplotlib - 模块sip没有属性setapi

带有自定义标头的 urllib.urlretrieve

Python 2 与 Python 3 - urllib 格式

为什么异步库比这个 I/O 绑定操作的线程慢?

如何阻止散景在 Jupyter Notebook 中打开新标签?