Python:将 PDF 转换为 blob 再转换回 pdf 会导致损坏

jOa*_*sis 2 python base64 blob

我正在测试我的 nosql 数据库设置的场景之一,其中我存储 PDF 数据 blob。稍后想用它是否可以检索原始pdf文档。为了测试它,我用 Python 编写了一个小测试代码。

import base64
with open('test.pdf', 'rb') as f:
 blob = base64.b64encode(f.read())

text_file = open('test_blob.txt', "w")
text_file.write(blob)
text_file.close()   

with open('test_blob.txt', 'r') as f:
  blob=f.read().decode('base64')
text_file = open('result.pdf', "w")
text_file.write(blob)
text_file.close()
Run Code Online (Sandbox Code Playgroud)

当我检查 result.pdf 时,它已损坏。可能是什么问题呢?

小智 6

我尝试了您提供的相同代码,但不幸的是我在解码部分遇到错误。我对代码做了一些修改。请尝试这个并让我知道它是否有效。

import base64
with open('path/sample.pdf', 'rb') as f:
    blob = base64.b64encode(f.read())
text_file = open('test_blob.txt', "wb")
text_file.write(blob)
text_file.close()
with open('test_blob.txt', 'r') as f:
    blob=f.read()
blob = base64.b64decode(blob)
text_file = open('result.pdf','wb')
text_file.write(blob)
text_file.close()
Run Code Online (Sandbox Code Playgroud)