在Python 3上将文件转换为base64字符串

Vla*_*r37 9 python base64 python-3.x

我需要将图像(或任何文件)转换为base64字符串.我使用不同的方式,但结果总是byte,而不是字符串.例:

import base64

file = open('test.png', 'rb')
file_content = file.read()

base64_one = base64.encodestring(file_content)
base64_two = base64.b64encode(file_content)

print(type(base64_one))
print(type(base64_two))
Run Code Online (Sandbox Code Playgroud)

<class 'bytes'>
<class 'bytes'>
Run Code Online (Sandbox Code Playgroud)

我如何获得字符串,而不是字节?Python 3.4.2.

tde*_*ney 19

Base64是一个ascii编码,因此您只需使用ascii进行解码即可

>>> import base64
>>> example = b'\x01'*10
>>> example
b'\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01'
>>> result = base64.b64encode(example).decode('ascii')
>>> print(repr(result))
'AQEBAQEBAQEBAQ=='
Run Code Online (Sandbox Code Playgroud)