如何使用Python GZip模块压缩文件夹?

Noa*_*h R 6 python compression gzip tar

我正在创建压缩文件/文件夹的Python软件......我如何创建一段代码,要求用户输入文件夹位置然后压缩它.我目前有单个文件的代码,但不是一个文件夹.请详细说明如何执行此操作.

小智 17

将文件夹压缩到tar文件的代码是:

import tarfile

tar = tarfile.open("TarName.tar.gz", "w:gz")
tar.add("folder/location", arcname="TarName")
tar.close()
Run Code Online (Sandbox Code Playgroud)

这个对我有用.希望对你也有用.


Fre*_*Foo 8

GZip不对文件夹/目录进行压缩,只对单个文件进行压缩.请改用zipfile模块.


Rus*_*ove 6

我不做UI,所以你可以自己从用户那里获取文件夹名称.这是制作gz压缩tarfile的一种方法.它没有递归子文件夹,你需要像os.walk()这样的东西.

# assume the path to the folder to compress is in 'folder_path'

import tarfile
import os

with tarfile.open( folder_path + ".tgz", "w:gz" ) as tar:
    for name in os.listdir( folder_path ):
        tar.add(name)
Run Code Online (Sandbox Code Playgroud)

  • 实际上你可以只写“tar.add(folder_path)”,它就会递归添加。(当然,这可能是自此答案发布以来五年内添加的新功能!)此外,for 循环不应在此处缩进,除非将 `tar = tarfile.open(...)` 更改为`with tarfile.open(...) as tar:` (这是一个好主意,然后你可以摆脱 `tar.close()` 行)。 (2认同)