Decoding binary to pdf

2020-05-09 07:52发布

I'm using a platform that, when you upload pdf's to it, converts the pdf with the base64 encode in Python. Then it stores the binary string in the database.

Now I want to decode the strings and write them to a local folder, so I thought to use the 'with open' structure and pass it the b parameter for binary and then it should create test.pdf based of my decoded string and write it to my desktop? Yet this yields no results, what am I doing wrong here?

code = "My binary string"

with open('test.pdf', 'wb') as fout:
     fout.write(base64.decode(code, '~/Desktop'))

EDIT:

code = "My binary string"

with open('~/Desktop/test.pdf', 'wb') as fout:
     fout.write(base64.decodestring(code))

Example binary string in database: "65/658e9014babd33786821f3130c5f3a1cc1322ddf" So I'm assuming it starts after the '/' mark?

标签: python base64
1条回答
可以哭但决不认输i
2楼-- · 2020-05-09 08:46

base64.decode(,) takes files as args. you want to try

fout.write(base64.decodestring(code))

though your code example is not encoded. Here's a working example:

#!/usr/bin/python
import base64, os
code = 'TXkgYmluYXJ5IHN0cmluZw==\n'
with open(os.path.expanduser('~/Desktop/test.pdf'), 'wb') as fout:
     fout.write(base64.decodestring(code))
查看更多
登录 后发表回答