如何在Python中压缩和解压缩文件?详细实现教程

2021年11月16日20:44:42 发表评论 905 次浏览

Python如何压缩和解压缩文件?了解如何使用 tarfile 内置模块中的 gzip 压缩在 Python 中压缩和解压缩文件、文件夹和符号链接。

压缩文件是一种存档文件,其中包含一个或多个已减小大小的文件。在现代操作系统中压缩文件通常非常简单。但是,在本教程中,你将学习如何使用 Python 编程语言压缩和解压缩文件。

如何在Python中压缩和解压缩文件?你可能会问,为什么我要学习用 Python 压缩文件,那里已经提供了工具?好吧,无需任何手动点击即可以编程方式解压缩文件非常有用。例如,在下载你希望下载一段代码的机器学习数据集时,自动提取它们并将其加载到内存中。

你可能还想在你的应用程序中添加压缩/解压功能,或者你有数千个压缩文件并且你想一键解压它们,本教程可以提供帮助。

相关: 如何在 Python 中加密和解密文件。

Python压缩和解压缩文件示例介绍 - 让我们开始吧,我们将使用tarfile内置模块,所以我们不需要安装任何东西,你可以选择安装tqdm只是为了打印进度条:

pip3 install tqdm

打开一个新的 Python 文件,然后:

import tarfile
from tqdm import tqdm # pip3 install tqdm

压缩

Python如何压缩和解压缩文件?首先让我们来压缩,下面的功能是负责压缩文件/文件夹或列表的文件/文件夹:

def compress(tar_file, members):
    """
    Adds files (`members`) to a tar_file and compress it
    """
    # open file for gzip compressed writing
    tar = tarfile.open(tar_file, mode="w:gz")
    # with progress bar
    # set the progress bar
    progress = tqdm(members)
    for member in progress:
        # add file/folder/link to the tar file (compress)
        tar.add(member)
        # set the progress description of the progress bar
        progress.set_description(f"Compressing {member}")
    # close the file
    tar.close()

我将这些文件/文件夹称为members,无论如何文档都是这么称呼它们的。

首先,我们打开并创建了一个新的用于gzip 压缩 写入的tar文件(这就是mode='w:gz'代表的意思),然后对于每个成员,将其添加到存档中,最后关闭tar文件。

我选择用tqdm包装成员以打印进度条,这在一次性压缩大量文件时非常有用。

这就是压缩,现在让我们深入了解减压。

还学习:如何在 Python 中压缩 PDF 文件。

解压缩

如何在Python中压缩和解压缩文件?以下函数用于解压缩给定的存档文件:

def decompress(tar_file, path, members=None):
    """
    Extracts `tar_file` and puts the `members` to `path`.
    If members is None, all members on `tar_file` will be extracted.
    """
    tar = tarfile.open(tar_file, mode="r:gz")
    if members is None:
        members = tar.getmembers()
    # with progress bar
    # set the progress bar
    progress = tqdm(members)
    for member in progress:
        tar.extract(member, path=path)
        # set the progress description of the progress bar
        progress.set_description(f"Extracting {member.name}")
    # or use this
    # tar.extractall(members=members, path=path)
    # close the file
    tar.close()

Python如何压缩和解压缩文件?首先,我们使用gzip压缩打开存档文件作为阅读。之后,我创建了一个可选参数“member”,以防我们想要提取特定文件(不是所有档案),如果未指定“members”,我们将使用getmembers()方法获取档案中的所有文件,该方法返回存档的所有成员作为 Python 列表。

Python压缩和解压缩文件示例解析:然后对于每个成员,使用extract()方法提取它,该方法从存档中提取一个成员到我们指定的“路径”目录。

请注意,我们也可以为此使用extractall()(官方文档中首选)。

让我们测试一下:

compress("compressed.tar.gz", ["test.txt", "folder"])

这会将当前目录中的test.txt文件和文件夹压缩为一个新的tar存档文件,名为compressed.tar.gz,如下例图所示:

如何在Python中压缩和解压缩文件?详细实现教程如果要解压:

decompress("compressed.tar.gz", "extracted")

这会将我们刚刚压缩的先前存档解压缩到一个名为提取的新文件夹中:

如何在Python中压缩和解压缩文件?详细实现教程

好的,我们完成了!你可以有创意,这里有一些想法:

  • 压缩文件夹后通过网络传输文件夹。
  • 下载存档文件并解压缩它们。

如何在Python中压缩和解压缩文件?在本教程中,我们探索了使用tarfile模块进行压缩和解压缩,你还可以使用zipfile模块处理ZIP档案、使用bz2模块进行bzip2压缩、gzip或用于gzip文件的zlib模块。

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: