【问题标题】:Convert file to base64 string on Python 3在 Python 3 上将文件转换为 base64 字符串
【发布时间】:2016-02-27 18:36:52
【问题描述】:

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

如何获取字符串而不是字节? Python 3.4.2。

【问题讨论】:

  • @AlastairMcCormack 我需要在文件中写入 base64 文本,然后再读取。

标签: python python-3.x base64


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    我需要在文件中写入 base64 文本...

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

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

    【讨论】:

    • 我很好的解决方案,但前提是您不将其他字符串写入文件。
    【解决方案3】:

    以下代码对我有用:

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

    我最初尝试过base64.encodestring(),但根据issue,该功能已被弃用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-07
      • 1970-01-01
      • 2021-05-01
      • 2021-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多