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

Convert file to base64 string on Python 3

我需要将图像(或任何文件)转换为 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))

返回

<class 'bytes'>
<class 'bytes'>

如何获取字符串而不是字节? Python3.4.2.

I need to write base64 text in file ...

那么别再担心字符串了,直接去做吧。

with open('output.b64', 'wb'):
  write(base64_one)

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=='

以下代码对我有用:

import base64

file_text = open(file, 'rb')
file_read = file_text.read()
file_encode = base64.encodebytes(file_read)

我最初尝试 base64.encodestring() 但该功能已被弃用 issue