Python 带有示例的 ZIP 文件
Python 允许您快速创建 zip/tar 档案。
以下命令将压缩整个目录
shutil.make_archive(output_filename, 'zip', dir_name)
以下命令可让你控制要存档的文件
ZipFile.write(filename)
以下是创建 Zip 文件的步骤 Python
步骤1) 从以下位置创建存档文件 Python,请确保导入语句正确且有序。以下是存档的导入语句 from shutil import make_archive
代码说明
- 从模块shutil导入make_archive类
- 使用split函数从路径中分离出目录和文件名到文本文件的位置(guru99)
- 然后我们调用模块“shutil.make_archive(“guru99 archive, “zip”, root_dir)”来创建存档文件,该文件将为 zip 格式
- 然后我们传入要压缩的内容的根目录。因此目录中的所有内容都将被压缩
- 运行代码时,您可以看到在面板右侧创建了存档 zip 文件。
步骤2) 创建存档文件后,您可以右键单击该文件并选择操作系统,它将显示您的存档文件,如下所示
现在您的 archive.zip 文件将出现在您的操作系统上(Windows 资源管理器)
步骤3) 双击该文件时,您将看到其中的所有文件的列表。
步骤4) In Python 我们可以对存档进行更多控制,因为我们可以定义要包含在存档下的特定文件。在我们的例子中,我们将在存档下包含两个文件 “guru99.txt” 和 “guru99.txt.bak”。
代码说明
- 从 zip 文件导入 Zipfile 类 Python 模块。此模块可完全控制创建 zip 文件
- 我们创建一个名为(“testguru99.zip,”w”)的新 Zipfile
- 创建一个新的 Zipfile 类,由于是文件,所以需要传入权限,所以需要将信息写入到文件中,如 newzip
- 我们使用变量“newzip”来引用我们创建的 zip 文件
- 使用“newzip”变量上的写入函数,我们将文件“guru99.txt”和“guru99.txt.bak”添加到档案中
执行代码时,您可以看到在面板右侧创建了名为“guru99.zip”的文件
备注:这里我们没有给出任何命令来“关闭”文件,如“newzip.close”,因为我们使用“With”范围锁,所以当程序超出这个范围时,文件将被清理并自动关闭。
步骤5) 当你 -> 右键单击文件 (testguru99.zip) 并 -> 选择您的操作系统 (Windows 资源管理器),它将显示文件夹中的存档文件,如下所示。
双击文件“testguru99.zip”时,它将打开另一个窗口,并显示其中包含的文件。
以下是完整的代码
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)”