Python中文件的base64编码

ste*_*fen 2 python base64 encoding

我想使用该函数base64.encode()直接在Python中对文件的内容进行编码。

文档指出

base64.encode(输入,输出)

对二进制输入文件的内容进行编码,并将生成的 Base64 编码数据写入输出文件。输入和输出必须是文件对象。

所以我这样做:

encode(open('existing_file.dat','r'), open('output.dat','w'))
Run Code Online (Sandbox Code Playgroud)

并得到以下错误:

>>> 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'
Run Code Online (Sandbox Code Playgroud)

在我看来,这看起来像是一个虫子,/usr/lib/python3.6/base64.py但我的很大一部分不愿意相信......

Aza*_*kov 7

来自文档

打开二进制文件时,应附加'b'模式值以以二进制模式打开文件

如此改变

encode(open('existing_file.dat','r'), open('output.dat','w'))
Run Code Online (Sandbox Code Playgroud)

encode(open('existing_file.dat','rb'), open('output.dat','wb'))
Run Code Online (Sandbox Code Playgroud)

应该管用