2017-06-19 69 views
1

我想使用函數base64.encode()直接對Python中文件的內容進行編碼。Python中的base64編碼

documentation狀態:

base64.encode(input, output)

Encode the contents of the binary input file and write the resulting base64 encoded data to the output file. input and output must be file objects.

所以我這樣做:

encode(open('existing_file.dat','r'), open('output.dat','w')) 

,並出現以下錯誤:

>>> import base64 
>>> base64.encode(open('existing_file.dat','r'), open('output.dat','w')) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/usr/lib/python3.6/base64.py", line 502, in encode 
    line = binascii.b2a_base64(s) 
TypeError: a bytes-like object is required, not 'str' 

爲了我的眼睛,看起來像在/usr/lib/python3.6/base64.py的錯誤但我很大一部分不想相信...

+0

嘗試打開字節模式文件:'rb' /'wb' –

回答

3

docs

when opening a binary file, you should append 'b' to the mode value to open the file in binary mode

因此更改

encode(open('existing_file.dat','r'), open('output.dat','w')) 

encode(open('existing_file.dat','rb'), open('output.dat','wb')) 

應該工作