2017-06-19 93 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')) 

应该工作