Python 中文件的 base64 编码

base64 encoding of file in Python

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

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 中的错误,但我的很大一部分不想相信...

来自 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'))

应该可以