title: Add multiple files from multiple directories to unique .tar.gz archives using Python
body: <p>I have directories of files that I need to add to a tar archive. The directory structure is:</p>
  
  <pre><code>..\root\path\dirname\somefiles.txt
  </code></pre>
  
  <p>and the .tar.gz files containing somefiles.ext should be deposited into ..\root\path\ as:</p>
  
  <pre><code>..\root\path\dirname.tar.gz
  </code></pre>
  
  <p>The code that I currently have is:</p>
  
  <pre><code>import os, tarfile
  
  for root, dirs, files in os.walk('.'):
      for dir in dirs:
          tar = tarfile.open(dir + '.tar.gz', 'w:gz')
          for file in files:
              tar.add(os.path.join(root, file))
          tar.close()
  </code></pre>
  
  <p>However, this pulls files from <code>..\root\path\</code> rather than <code>..\root\path\dirname\</code>. How can I write this to pull the files out of each directory and add them to the archive of the same name of the directory?</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>With the use of @mVChr's code, I was able to obtain what I needed. I added <code>arcname=f</code> to remove the directory within the archive; I have no idea why I did not implement this before:</p>
  
  <pre><code>import os, tarfile
  
  for root, dirs, _ in os.walk('.'):
      for d in dirs:
          with tarfile.open(d + '.tar.gz', 'w:gz') as tar:
              for _, _, files in os.walk(os.path.join(root, d)):
                  for f in files:
                      tar.add(os.path.join(root, d, f), arcname=f)
  </code></pre>