如何使用 Python 将文件添加到 tarfile 中,而不添加目录层次结构?

当我在具有文件路径的 tarfile对象上调用 add()时,该文件被添加到具有关联目录层次结构的 tarball 中。换句话说,如果我解压缩 tarfile 文件,原始目录层次结构中的目录将被重现。

有没有一种方法可以简单地添加一个没有目录信息的普通文件,解压缩得到的 tarball 会产生一个文件的平面列表?

63017 次浏览

You can use tarfile.addfile(), in the TarInfo object, which is the first parameter, you can specify a name that's different from the file you're adding.

This piece of code should add /path/to/filename to the TAR file but will extract it as myfilename:

tar.addfile(tarfile.TarInfo("myfilename.txt"), open("/path/to/filename.txt"))

Maybe you can use the "arcname" argument to TarFile.add(name, arcname). It takes an alternate name that the file will have inside the archive.

Using the arcname argument of TarFile.add() method is an alternate and convenient way to match your destination.

Example: you want to archive a dir repo/a.git/ to a tar.gz file, but you rather want the tree root in the archive begins by a.git/ but not repo/a.git/, you can do like followings:

archive = tarfile.open("a.git.tar.gz", "w|gz")
archive.add("repo/a.git", arcname="a.git")
archive.close()

thanks to @diabloneo, function to create selective tarball of a dir

def compress(output_file="archive.tar.gz", output_dir='', root_dir='.', items=[]):
"""compress dirs.


KWArgs
------
output_file : str, default ="archive.tar.gz"
output_dir : str, default = ''
absolute path to output
root_dir='.',
absolute path to input root dir
items : list
list of dirs/items relative to root dir


"""
os.chdir(root_dir)
with tarfile.open(os.path.join(output_dir, output_file), "w:gz") as tar:
for item in items:
tar.add(item, arcname=item)




>>>root_dir = "/abs/pth/to/dir/"
>>>compress(output_file="archive.tar.gz", output_dir=root_dir,
root_dir=root_dir, items=["logs", "output"])

If you want to add the directory name but not its contents inside a tarfile, you can do the following:

(1) create an empty directory called empty (2) tf.add("empty", arcname=path_you_want_to_add)

That creates an empty directory with the name path_you_want_to_add.

Here is the code sample to tar list of files in folder without adding folder:

    with tarfile.open(tar_path, 'w') as tar:
for filename in os.listdir(folder):
fpath = os.path.join(folder, filename)
tar.add(fpath, arcname=filename)