Python 3.x 在python中压缩tar.gz文件时如何包含目录?

Python 3.x 在python中压缩tar.gz文件时如何包含目录?,python-3.x,tarfile,Python 3.x,Tarfile,以下是我想做的: 导入文件 path=os.path.join(存档路径,“package.tar.gz”) tar_package=tarfile.open(路径“w:gz”) chdir(os.path.join(归档路径,“包”)) 对于os.listdir(“.”)中的名称: tar_包。添加(名称) tar_package.close() 这是将文件直接卸载到其文件内容。像这样: #卸载tar文件 tar-xf package.tar.gz (直接从指定位置的包/中删除文件。) 我

以下是我想做的:

导入文件
path=os.path.join(存档路径,“package.tar.gz”)
tar_package=tarfile.open(路径“w:gz”)
chdir(os.path.join(归档路径,“包”))
对于os.listdir(“.”)中的名称:
tar_包。添加(名称)
tar_package.close()
这是将文件直接卸载到其文件内容。像这样:

#卸载tar文件
tar-xf package.tar.gz
(直接从指定位置的包/中删除文件。)

我想将文件解压为其目录名,其中包含文件内容。像这样:

#卸载tar文件
tar-xf package.tar.gz
包/(此位置包内的文件)


这是我第一次在python中使用tarfile。如果有帮助的话——我正在使用python 3.6。非常感谢您的帮助。

tarfile.add
支持目录,因此您可以直接添加
“package”
,而不是循环查看其内容,您将得到您想要的结果:

import tarfile
import os

path = os.path.join(archive_path,"package.tar.gz")
tar_package = tarfile.open(path, "w:gz")
os.chdir(archive_path)
tar_package.add("package")
tar_package.close()
您可以指定不同的目录名作为添加的第二个参数:

tar_package.add("package", "custom dir name")
还可以为各个文件指定子目录:

for name in os.listdir("."):
    tar_package.add(name, os.path.join("custom subdir", name))