Skip to content

Instantly share code, notes, and snippets.

@develost
Last active March 6, 2023 17:33
Show Gist options
  • Save develost/a7630158e2c0de74cb66 to your computer and use it in GitHub Desktop.
Save develost/a7630158e2c0de74cb66 to your computer and use it in GitHub Desktop.
From postgres bytea to file (a PDF for example)
# Execute select in pgAdmin
# write result to file
"""
select encode(my_bin_field,'base64')
from my_schema.my_table
where id=123;
"""
# Remove column name from generated file
import base64
recovered = base64.decodestring(open("my_base64_file","r").read())
f = open("my_bin_file.pdf", "wb")
f.write(recovered)
f.close()
Copy link

ghost commented Aug 7, 2017

Thanks for the piece of code! For me, changing to binary reading mode ('rb') made it work:

recovered = base64.decodestring(open("my_base64_file","rb").read())

@chakravarthik27
Copy link

Thanks for sharing this code, but I found some errors like

AttributeError: module 'base64' has no attribute 'decodestring'

Now I made changes like decodestring to decodebytes,

recovered = base64.decodebytes(open("my_base64_file","rb").read())
it's working with the above line of code.

#python3.8 #base64

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment