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

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

我正在尝试对 python 中的 pdf 进行 base64 编码。对此的几个 SO 答案适用于其他人,但由于某种原因不适用于我。我最近的尝试是:

# 
with open('/home/cchilders/projects/myproject/data/books/software-and-mind.pdf', 'rb') as f:
    encoded = f.read().encode("base64")
    print(encoded)

我明白了

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

我怎样才能base64这个pdf文件?谢谢

你应该为此使用 base64 模块

import base64
base64.b64encode(f.read())