繁体   English   中英

如何在 Python 中将 base64 文件解码为二进制文件?

[英]How to decode base64 file into binary in Python?

我正在构建一个处理 pdf 文件数据的系统(为此我使用PyPDF2 lib )。 我现在获得了一个 base64 编码的 PDF,我可以使用以下方法正确解码和存储它:

import base64
# base64FileData  <= the base64 file data
fileData = base64.urlsafe_b64decode(base64FileData.encode('UTF-8'))
with open('thefilename.pdf', 'w') as theFile:
    theFile.write(fileData)

我现在想使用这个fileData作为一个二进制文件来拆分它,但是当我做type(fileData)fileData结果是一个<type 'str'> 如何将此fileData转换为二进制(或至少不是字符串)?

欢迎所有提示!

[编辑]

如果我open(fileData, 'rb')我得到一个错误,说

类型错误:file() 参数 1 必须是没有 NULL 字节的编码字符串,而不是 str

要删除我尝试过的空字节, fileData.rstrip(' \\t\\r\\n\\0')fileData.rstrip('\\0')fileData.partition(b'\\0')[0] ,但没有似乎工作。 有任何想法吗?

[编辑2]

问题是我将此字符串传递给PyPDF2 PdfFileReader 类该类第 909 至 912 行执行以下操作(其中stream是我提供的fileData ):

if type(stream) in (string_type, str):
    fileobj = open(stream, 'rb')
    stream = BytesIO(b_(fileobj.read()))
    fileobj.close()

因此,因为它是一个字符串,所以它假定它是一个文件名,然后它会尝试打开该文件。 然后失败并显示TypeError 因此,在将fileData给 PdfFileReader 之前,我需要以某种方式将其转换为str以外的其他内容,以便它不会尝试打开它,而只是将fileData视为fileData的文件。 有任何想法吗?

因此打开的二进制模式你必须使用 'wb' 否则它基本上被保存为“文本”。

import base64
# base64FileData  <= the base64 file data
fileData = base64.urlsafe_b64decode(base64FileData.encode('UTF-8'))
with open('thefilename.pdf', 'wb') as theFile:
    theFile.write(fileData)

示例您的输入数据来自于此:

with open(local_image_path, "rb") as imageFile:
    str_image_data = base64.b64encode(imageFile.read())

然后要获取变量中的二进制文件,您可以尝试:

import io
import base64

binary_image_data = io.BytesIO(base64.decodebytes(str_image_data))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM