2016-02-27 92 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

相關問題