【发布时间】:2011-01-03 04:41:03
【问题描述】:
如何在 Python 中创建带压缩的 .tar.gz 文件?
【问题讨论】:
-
tar 不压缩数据,它只是将文件打包在一起。实际压缩的是 gzip。
标签: python compression zip tarfile
如何在 Python 中创建带压缩的 .tar.gz 文件?
【问题讨论】:
标签: python compression zip tarfile
在这 tar.gz 文件在打开的视图目录中压缩 在解决使用 os.path.basename(file_directory)
import tarfile
with tarfile.open("save.tar.gz","w:gz") as tar:
for file in ["a.txt","b.log","c.png"]:
tar.add(os.path.basename(file))
它在 tar.gz 文件中的使用 压缩在目录中
【讨论】:
. 和.. 的最佳性能!subprocess.call(f'tar -cvzf {output_filename} *', cwd=source_dir, shell=True)
cwd 参数在压缩前更改目录 - 这解决了点的问题。
shell=True 允许使用通配符 (*)
也适用于递归目录
【讨论】:
对@THAVASI.T 的回答进行了小幅更正,其中省略了显示“tarfile”库的导入,并且没有定义第三行中使用的“tar”对象。
import tarfile
with tarfile.open("save.tar.gz","w:gz") as tar:
for file in ["a.txt","b.log","c.png"]:
tar.add(os.path.basename(file))
【讨论】:
除了@Aleksandr Tukallo 的回答,您还可以获得输出和错误消息(如果发生)。 following answer 上很好地解释了使用 tar 压缩文件夹。
import traceback
import subprocess
try:
cmd = ['tar', 'czfj', output_filename, file_to_archive]
output = subprocess.check_output(cmd).decode("utf-8").strip()
print(output)
except Exception:
print(f"E: {traceback.format_exc()}")
【讨论】:
为整个目录树构建.tar.gz(又名.tgz):
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))
这将创建一个 gzipped tar 存档,其中包含一个顶级文件夹,其名称和内容与 source_dir 相同。
【讨论】:
arcname=os.path.basename(source_dir),那么它将在tar 文件中为你提供source_dir 的整个路径结构(在大多数情况下,这可能很不方便)。
arcname=os.path.basename(source_dir) 仍然意味着存档包含一个包含source_dir 内容的文件夹。如果您希望存档的根目录包含内容本身,而不是文件夹中的内容,请改用arcname=os.path.sep。
os.path.sep,那么存档将包含服务“。”或“/”文件夹,这通常不是问题,但如果您以后以编程方式处理此存档,有时可能会成为问题。似乎唯一真正干净的方法是做os.walk 并单独添加文件
arcname='.'。无需使用os.walk。
以前的答案建议使用tarfile Python 模块在Python 中创建.tar.gz 文件。这显然是一个很好的 Python 风格的解决方案,但它在归档速度方面存在严重缺陷。 This question 提到 tarfile 比 Linux 中的 tar 实用程序慢大约两倍。根据我的经验,这个估计是非常正确的。
因此,为了更快地归档,您可以使用 tar 命令和 subprocess 模块:
subprocess.call(['tar', '-czf', output_filename, file_to_archive])
【讨论】:
import tarfile
tar = tarfile.open("sample.tar.gz", "w:gz")
for name in ["file1", "file2", "file3"]:
tar.add(name)
tar.close()
如果要创建 tar.bz2 压缩文件,只需将文件扩展名替换为“.tar.bz2”,将“w:gz”替换为“w:bz2”即可。
【讨论】:
with tarfile.open( ..,而不是手动调用open 和close。打开常规文件时也是如此。
你用mode='w:gz'调用tarfile.open,意思是“打开gzip压缩写入”。
您可能希望以 .tar.gz 结束文件名(open 的 name 参数),但这不会影响压缩能力。
顺便说一句,使用'w:bz2' 模式通常可以获得更好的压缩效果,就像tar 通常使用bzip2 压缩比使用gzip 压缩更好。
【讨论】: