[英]Convert file to base64 string on Python 3
I need to convert image (or any file) to base64 string.我需要将图像(或任何文件)转换为 base64 字符串。 I use different ways, but result is always byte
, not string.我使用不同的方式,但结果始终是byte
,而不是字符串。 Example:例子:
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))
Returned回来
<class 'bytes'>
<class 'bytes'>
How do I get a string, not byte?我如何得到一个字符串,而不是字节? Python 3.4.2. Python 3.4.2。
Base64 is an ascii encoding so you can just decode with ascii 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=='
I need to write base64 text in file ... 我需要在文件中写入base64文本...
So then stop worrying about strings and just do that instead. 所以,不要再担心字符串而只是这样做。
with open('output.b64', 'wb'):
write(base64_one)
The following code worked for me:以下代码对我有用:
import base64
file_text = open(file, 'rb')
file_read = file_text.read()
file_encode = base64.encodebytes(file_read)
I initially tried base64.encodestring()
but that function has been deprecated as per this issue .我最初尝试base64.encodestring()
但 function 已根据此问题弃用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.