Reading a tarfile into BytesIO
<p>I'm using <a href="https://docker-py.readthedocs.io/en/latest/api/#put_archive" rel="nofollow">Docker-py</a> API to handle and manipulate <code>Docker</code> containers. In the <code>API</code>, the <code>put_archive</code> function expects the <code>data</code> field to be in bytes.
So, using the <code>tarfile</code> library I have:</p>

<pre><code>import tarfile
import io

container = client.create_container(image="myimage", command="/bin/bash")
source = "~/.ssh/id_rsa.pub"
tarfile = create_tar_file(path=source, name="keys.tar")
# tarfile = "keys.tar"
# How can I read the tar file was a BytesIO() object?
data = io.BytesIO()
client.put_archive(container=container, path="/tmp", data=data)
</code></pre>

<p>The API says:</p>

<blockquote>
  <p>put_archive</p>
  
  <p>Insert a file or folder in an existing container using a tar archive as source.</p>
  
  <p>Params:</p>
  
  <p>container (str): The container where the file(s) will be extracted
     path (str): Path inside the container where the file(s) will be extracted. Must exist.
     data (bytes): tar data to be extracted
     Returns (bool): True if the call succeeds. docker.errors.APIError will be raised if an error occurs.</p>
</blockquote>

<p>My Question is: How can I read the tar file as a <code>BytesIO()</code> so it can be passed to the <code>put_archive()</code> function?</p>

<p>You could do this way (untested because I don't have<code>Docker-py</code> installed):</p>

<pre><code>with open('keys.tar', 'rb') as fin:
    data = io.BytesIO(fin.read())
</code></pre>

python byte tar