本文介绍了二进制文件的Python 3和base64编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm new to Python and I do have an issue that is bothering me.

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

I use the following code to get a base64 string representation of my zip file.

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

现在,如果我输出的字符串包含在b''表示形式中.这对我来说不是必需的,我想避免这种情况.此外,它每76个字符添加一个换行符,这是另一个问题.有没有一种方法来获取二进制内容并在没有换行符的情况下表示该内容,并在末尾加上前导b''?

Now, if I output the string it is contained inside a b'' representation. This for me is not necessary and I would like to avoid it. Also it adds a newlines character every 76 characters which is another issue. Is there a way to get the binary content and represent it without the newline characters and trailing and leading b''?

仅供比较,如果我在PowerShell中执行以下操作:

Just for comparison, if I do the following in PowerShell:

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

我确实得到了我要查找的确切字符串,每76个字符都没有b''和\ n.

I do get the exact string I'm looking for, no b'' and no \n every 76 chars.

推荐答案

来自 base64程序包doc:

"对可能包含任意二进制数据的类似字节的对象s进行编码,并返回包含base64编码数据的bytes,并在每输出76个字节后插入换行符(b"\n"),并确保遵循RFC 2045(MIME)的结尾换行."

"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编码类似字节的对象,并返回已编码的bytes."

示例:

import base64

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

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

The decode() will convert the binary string to text.

这篇关于二进制文件的Python 3和base64编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 16:43