2016-02-27 95 views
2

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

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。

+0

@AlastairMcCormack我需要写的base64文本文件,然后以后读它。 – Vladimir37

回答

9

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

我需要写在文件的base64的文字...

所以再不用担心字符串,只是做到这一点吧。

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

我很好的解决方案,但只有当你不写入其他字符串的文件。 – tdelaney

相关问题