tarfile - Adding files from different drives
<p>I am trying to archive and compress multiple directories spread along multiple drives using the tarfile library.
The problem is that tarfile merges the paths even if two files are stored in different drives.
For example:</p>

<pre><code>import tarfile
with tarfile.open(r"D:\Temp\archive.tar.gz", "w:gz") as tf:
    tf.add(r"C:\files\foo")
    tf.add(r"D:\files\bar")
</code></pre>

<p>Will create an archive containing the following files:</p>

<pre><code>archive.tar.gz
|
    files
    |
        foo
        bar
</code></pre>

<p>Is there a way of creating this:</p>

<pre><code>archive.tar.gz
|
    C
    |
        files
        |
            foo
    D
    |
        files
        |
            bar
</code></pre>

<p>Thanks in advance.</p>

<p>Thanks <strong>LoÃ¯c</strong> for your answer, it helped me find the actual answer I was looking for. (And also made me waste about a hour because I got really confused with the linux and windows style paths you mixed up in your answer)...</p>

<pre><code>import os
import tarfile

def create_archive(paths, arc_paths, archive_path):
    with tarfile.open(archive_path, "w:gz") as tf:
        for path, arc_path in zip(paths, arc_paths):
            tf.add(path, arcname=arc_path)

def main():
    archive = r"D:\Temp\archive.tar.gz"
    paths = [r"C:\files\foo", r"D:\files\bar"]
    # Making sure all the paths are absolute.
    paths = [os.path.abspath(path) for path in paths]
    # Creating arc-style paths
    arc_paths = [path.replace(':', '') for path in paths]
    # Create the archive including drive letters (if in windows)
    create_archive(paths, arc_paths, archive)
</code></pre>

python gzip tar tarfile