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

发布于 2024-09-26 01:17:35 字数 106 浏览 2 评论 0原文

我正在创建压缩文件/文件夹的 Python 软件...我将如何创建一段代码,要求用户输入文件夹位置,然后对其进行压缩。我目前拥有单个文件的代码,但没有包含完整文件的文件夹。请详细解释如何执行此操作。

I'm creating Python software that compresses files/folders... How would I create a section of the code that asks for the user input of the folder location and then compresses it. I currently have the code for a single file but not a folder full of files. Please explain in detail how to do this.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

活泼老夫 2024-10-03 01:17:35

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

import tarfile

tar = tarfile.open("TarName.tar.gz", "w:gz")
tar.add("folder/location", arcname="TarName")
tar.close()

它对我有用。希望这也适合你。

The code to compress a folder in to tar file is:

import tarfile

tar = tarfile.open("TarName.tar.gz", "w:gz")
tar.add("folder/location", arcname="TarName")
tar.close()

It works for me. Hope that works for you too.

眼泪淡了忧伤 2024-10-03 01:17:35

我不做用户界面,所以你需要自己从用户那里获取文件夹名称。这是制作 gz 压缩 tar 文件的一种方法。它不会在子文件夹上递归,你需要像 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)

I don't do UI, so you're on your own for getting the folder name from the user. Here's one way to make a gz-compressed tarfile. It does not recurse over subfolders, you'll need something like os.walk() for that.

# 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)
做个少女永远怀春 2024-10-03 01:17:35

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

GZip doesn't do compression of folders/directories, only single files. Use the zipfile module instead.

万劫不复 2024-10-03 01:17:35

正如 larsmans 所说,gzip 压缩不用于目录,仅用于单个文件。使用 Linux 的常用方法是先将目录放入 tarball 中,然后对其进行压缩。

As larsmans says, gzip compression is not used for directories, only single files. The usual way of doing things with linux is to put the directory in a tarball first and then compress it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文