title: How to append a file to a tar file use python tarfile module?
body: <p>I want to append a file to the tar file. For example, the files in <code>test.tar.gz</code> are <code>a.png, b.png, c.png</code>. I have a new png file named <code>a.png</code>, I want to append to <code>a.png</code> to <code>test.tar.gz</code> and cover the old file <code>a.png</code> in <code>test.tar.gz</code>. My code:</p>
  
  <pre><code>import tarfile
  a = tarfile.open('test.tar.gz', 'w:gz')
  a.add('a.png')
  a.close()
  </code></pre>
  
  <p>then, all the files in <code>test.tar.gz</code> disappeard but <code>a.png</code>, if I change my code to this:</p>
  
  <pre><code>import tarfile
  a = tarfile.open('test.tar.gz', 'a:')# or a:gz
  a.add('a.png')
  a.close()
  </code></pre>
  
  <p>the program is crashed, error log:</p>
  
  <pre><code>Traceback (most recent call last):
    File "&lt;stdin&gt;", line 1, in &lt;module&gt;
    File "/usr/lib/python2.7/tarfile.py", line 1678, in open
      return func(name, filemode, fileobj, **kwargs)
    File "/usr/lib/python2.7/tarfile.py", line 1705, in taropen
      return cls(name, mode, fileobj, **kwargs)
    File "/usr/lib/python2.7/tarfile.py", line 1588, in __init__
      raise ReadError(str(e))
  tarfile.ReadError: invalid header
  </code></pre>
  
  <p>What are my mistakes and what should I do?</p>
  
  <p><strong>Update</strong>. From the documentation, it follows that <code>gz</code> files cannot be open in <code>a</code> mode. If so, what is the best way to add or update files in an existing archive?</p>