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

时间:2016-09-01 19:04:11

标签: python gzip tar 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

2 个答案:

答案 0 :(得分:4)

您需要使用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')

答案 1 :(得分:0)

感谢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)