Python ZIP 文件及示例

Python 允许您快速创建 zip/tar 归档。

以下命令将压缩整个目录

shutil.make_archive(output_filename, 'zip', dir_name)

以下命令让您可以控制要归档的文件

ZipFile.write(filename)

以下是使用 Python 创建 Zip 文件的步骤

第 1 步: 要从 Python 创建归档文件,请确保您的导入语句正确且顺序正确。此处归档的导入语句为 from shutil import make_archive

Python ZIP file

代码解释

  • 从 shutil 模块导入 make_archive 类
  • 使用 split 函数从文本文件(guru99)的位置路径中分离出目录和文件名
  • 然后我们调用模块“shutil.make_archive(“guru99 archive, “zip”, root_dir)”来创建归档文件,该文件将是 zip 格式
  • 之后,我们将要被压缩的内容的根目录传递进去。这样目录中的所有内容都会被压缩
  • 当您运行代码时,您可以在面板的右侧看到归档 zip 文件已创建。

第 2 步: 归档文件创建完成后,您可以右键单击该文件并选择操作系统,它将显示其中的归档文件,如下所示

Python ZIP file

现在您的 archive.zip 文件将出现在您的操作系统(Windows Explorer)中

Python ZIP file

第 3 步: 当您双击该文件时,您将看到其中所有文件的列表。

Python ZIP file

第 4 步: 在 Python 中,我们可以更精确地控制归档,因为我们可以定义要包含在归档中的特定文件。在我们的例子中,我们将包含两个文件在归档中:“guru99.txt”“guru99.txt.bak”

Python ZIP file

代码解释

  • 从 zipfile Python 模块导入 Zipfile 类。该模块提供了对创建 zip 文件的完全控制
  • 我们创建一个名为(“testguru99.zip,“w”)的新 Zipfile
  • 创建新的 Zipfile 类需要传递权限,因为它是文件,所以您需要将信息写入文件,如 newzip
  • 我们使用变量“newzip”来引用我们创建的 zip 文件
  • 通过在“newzip”变量上使用 write 函数,我们将文件“guru99.txt”和“guru99.txt.bak”添加到归档中

当您执行代码时,您可以在面板的右侧看到已创建的文件,名为“guru99.zip”

注意:这里我们没有像“newzip.close”那样给出“关闭”文件的命令,因为我们使用了“With”作用域锁定,当程序退出此作用域时,文件将被自动清理并关闭。

第 5 步: 当您-> 右键单击文件(testguru99.zip)并 -> 选择您的操作系统(Windows Explorer)时,它将显示文件夹中的归档文件,如下所示。

Python ZIP file

当您双击文件“testguru99.zip”时,它将打开另一个窗口,其中显示了包含在其中的文件。

Python ZIP file

这是完整的代码

Python 2 示例

import os
import shutil
from zipfile import ZipFile
from os import path
from shutil import make_archive

def main():
# Check if file exists
	if path.exists("guru99.txt"):
# get the path to the file in the current directory
	src = path.realpath("guru99.txt");
# rename the original file
	os.rename("career.guru99.txt","guru99.txt")
# now put things into a ZIP archive
	root_dir,tail = path.split(src)
    shutil.make_archive("guru99 archive", "zip", root_dir)
# more fine-grained control over ZIP files
	with ZipFile("testguru99.zip","w") as newzip:
	newzip.write("guru99.txt")
	    newzip.write("guru99.txt.bak")
if __name__== "__main__":
	  main()

Python 3 示例

import os
import shutil
from zipfile import ZipFile
from os import path
from shutil import make_archive

    # Check if file exists
       if path.exists("guru99.txt"):
    # get the path to the file in the current directory
        src = path.realpath("guru99.txt");
    # rename the original file
        os.rename("career.guru99.txt","guru99.txt")
    # now put things into a ZIP archive
        root_dir,tail = path.split(src)
        shutil.make_archive("guru99 archive","zip",root_dir)
    # more fine-grained control over ZIP files
        with ZipFile("testguru99.zip", "w") as newzip:
            newzip.write("guru99.txt")
            newzip.write("guru99.txt.bak")

摘要

  • 要压缩整个目录,请使用命令“shutil.make_archive(“name”,”zip”, root_dir)”
  • 要选择要压缩的文件,请使用命令“ZipFile.write(filename)”