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

2024-04-18 07:08:51 发布

您现在位置: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')我会得到一个错误,说

TypeError: file() argument 1 must be encoded string without NULL bytes, not str

为了删除空字节,我尝试了fileData.rstrip(' \t\r\n\0')fileData.rstrip('\0')fileData.partition(b'\0')[0],但似乎没有任何效果。有什么想法吗?在

[编辑2]

问题是我将这个字符串传递给PyPDF2 PdfFileReader class,后者在lines 909 to 912上执行以下操作(其中stream是我提供的fileData):

^{pr2}$

因为它是一个字符串,所以它假设它是一个文件名,然后它试图打开文件。这将失败,并出现一个TypeError。因此,在将fileData提供给PdfFileReader之前,我需要以某种方式将其转换为str之外的其他文件,这样它就不会试图打开它,而只考虑fileData本身就是一个文件。有什么想法吗?在


Tags: 文件字符串编辑pdftype二进制openfile
1条回答
网友
1楼 · 发布于 2024-04-18 07:08:51

因此open的binary mode你必须使用'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)

相关问题 更多 >