简体   繁体   English

Python中文件的base64编码

[英]base64 encoding of file in Python

I want to use the function base64.encode() to directly encode the contents of a file in Python. 我想使用base64.encode()函数直接在Python中编码文件的内容。

The documentation states: 文档指出:

base64.encode(input, output) base64.encode(输入,输出)

Encode the contents of the binary input file and write the resulting base64 encoded data to the output file. 对二进制输入文件的内容进行编码,然后将生成的base64编码数据写入输出文件。 input and output must be file objects. 输入和输出必须是文件对象。

So I do this: 所以我这样做:

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

and get the following error: 并得到以下错误:

>>> 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'

To my eye that looks like a bug in /usr/lib/python3.6/base64.py but a big part of me does not want to believe that... 在我看来,这看起来像是/usr/lib/python3.6/base64.py的错误,但是我的很大一部分不想相信...

from docs 来自docs

when opening a binary file, you should append 'b' to the mode value to open the file in binary mode 打开二进制文件时,应在模式值后附加'b'以二进制模式打开文件

so changing 所以改变

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

to

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

should work 应该管用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM