title: base64 encoding of file in Python
body: <p>I want to use the function <code>base64.encode()</code> to directly encode the contents of a file in Python.</p>
  <p>The <a href="https://docs.python.org/3.6/library/base64.html#base64.encode" rel="nofollow noreferrer">documentation</a> states:</p>
  <blockquote>
  <p><strong>base64.encode(input, output)</strong></p>
  <p>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.</p>
  </blockquote>
  <p>So I do this:</p>
  <pre><code>encode(open('existing_file.dat','r'), open('output.dat','w'))
  </code></pre>
  <p>and get the following error:</p>
  <pre><code>&gt;&gt;&gt; import base64
  &gt;&gt;&gt; base64.encode(open('existing_file.dat','r'), open('output.dat','w'))
  Traceback (most recent call last):
    File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;
    File &quot;/usr/lib/python3.6/base64.py&quot;, line 502, in encode
      line = binascii.b2a_base64(s)
  TypeError: a bytes-like object is required, not 'str'
  </code></pre>
  <p>To my eye that looks like a bug in <code>/usr/lib/python3.6/base64.py</code> but a big part of me does not want to believe that...</p>