欢迎访问宙启技术站
智能推送

使用Bundle()函数在Python中进行文件压缩和解压缩

发布时间:2024-01-13 02:04:46

在Python中,我们可以使用shutil模块来进行文件的压缩和解压缩操作。该模块提供了make_archive()unpack_archive()函数,它们可以使用zipfile库来实现文件的压缩和解压缩。

下面是一个使用make_archive()函数进行文件压缩的示例:

import shutil

# 创建一个目录,并在其中添加一些文件
shutil.rmtree("example_dir", ignore_errors=True)
shutil.rmtree("example.zip", ignore_errors=True)
shutil.rmtree("example.tar.gz", ignore_errors=True)
shutil.rmtree("example.tar.bz2", ignore_errors=True)

with open("example_dir/file1.txt", "w") as f:
    f.write("This is file 1.")

with open("example_dir/file2.txt", "w") as f:
    f.write("This is file 2.")

# 压缩文件
shutil.make_archive("example", "zip", ".", "example_dir")

print("文件压缩完成!")

上述代码首先创建了一个名为example_dir的目录,并在其中添加了两个文件。然后,通过make_archive()函数将该目录压缩为一个example.zip文件。该函数接收四个参数:压缩文件名、压缩格式、要压缩的目录或文件路径以及要压缩的目录或文件名。运行代码后,会在当前目录下生成example.zip文件。

接下来,让我们看一个使用unpack_archive()函数进行文件解压缩的示例:

import shutil

# 解压缩文件
shutil.unpack_archive("example.zip", ".", "zip")

print("文件解压缩完成!")

上述代码使用unpack_archive()函数将example.zip文件解压缩到当前目录中。该函数接收三个参数:要解压缩的文件名、解压缩的目标路径以及解压缩的格式。运行代码后,会将example.zip文件解压缩到当前目录。

以上就是使用shutil模块进行文件压缩和解压缩的基本操作。除了zip格式,make_archive()函数还支持其他常见的压缩格式,包括targztarbztar等。你可以根据需要选择合适的格式来进行文件压缩。