AttributeError: 'bytes' object has no attribute 'encode'; base64 encode a pdf file

25,929

you should use the base64 module for this

import base64
base64.b64encode(f.read())
Share:
25,929
codyc4321
Author by

codyc4321

Updated on March 26, 2020

Comments

  • codyc4321
    codyc4321 about 4 years

    I am trying to base64 encode a pdf in python. Several SO answers to this worked for other people but not on my end for some reason. My most recent attempt is:

    # http://stackoverflow.com/questions/12020885/python-converting-file-to-base64-encoding
    with open('/home/cchilders/projects/myproject/data/books/software-and-mind.pdf', 'rb') as f:
        encoded = f.read().encode("base64")
        print(encoded)
    

    I get

    AttributeError: 'bytes' object has no attribute 'encode'
    

    How can I base64 this pdf file? Thank you