使用tarfile在Python中创建tar文件,使目录树位于tar.gz中



为了创建tar.gz文件,我使用以下代码。

import os
import tarfile
def tardir(path, tar_name):
with tarfile.open(tar_name, "w:gz") as tar_handle:
for root, dirs, files in os.walk(path):
for file in files:
tar_handle.add(os.path.join(root, file))
tardir('C:/../../projects/project_folder', 'C:/../../projects/project_folder/tar_files/tar_file.tar.gz')
tar.close()

我想要gzip tar_files文件夹,当我解压缩它时,我只想看到这个文件夹。但在上面的代码中,在tar文件中,我看到它用目录树存储。就像当我打开它时,我看到下面的文件夹

/..//项目/项目_文件夹

如何解决此问题?感谢回答

下面链接中的代码解决了我的问题。

如何使用Python创建完整的压缩tar文件?

import tarfile
import os.path
def make_tarfile(output_filename, source_dir):
with tarfile.open(output_filename, "w:gz") as tar:
tar.add(source_dir, arcname=os.path.basename(source_dir))

为参数output_filnamesource_dir提供绝对地址适用于

最新更新