在 tarfile 中区分来自不同驱动器的文件

Discriminate files from different drives in tarfile

我正在尝试使用 tarfile 库归档和压缩分布在多个驱动器上的多个目录。 问题是即使两个文件存储在不同的驱动器中,tarfile 也会合并路径。 例如:

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")

将创建包含以下文件的存档:

archive.tar.gz
└─ files
   ├─ foo
   └─ bar

有没有办法创建这个?

archive.tar.gz
├─ C
|  └─ files
|     └─ foo
└─ D
   └─ files
      └─ bar

您需要使用 tarfile.addfile() 而不是 tarfile.add() :

使用 TarInfo,您可以指定将在存档中使用的文件名。

例子:

with open(r"C:\files\foo", "rb") as ff:
    ti = tf.gettarinfo(arcname="C/files/foo", fileobj=ff)
    tf.addfile(ti, ff)

或者,一个更快的解决方案:

tf.add('/path/to/dir/to/add/', arcname='C/files')
tf.add('/path/to/otherdir/to/add/', arcname='D/files')

感谢 Loïc 的回答,它帮助我找到了我正在寻找的实际答案。 (也让我浪费了大约一个小时,因为我对你在回答中混淆的 linux 和 windows 样式路径感到非常困惑)...

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)