专业编程基础技术教程

网站首页 > 基础教程 正文

DAY5-step5 Python 示例说明 ZIP 压缩文件

ccvgpt 2024-08-06 12:39:52 基础教程 13 ℃

Python使您可以快速创建zip或者tar压缩文档。

以下命令将压缩整个目录

DAY5-step5 Python 示例说明 ZIP 压缩文件

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

以下命令使您可以控制要压缩的文件

ZipFile.write(filename)

以下是在Python中创建Zip文件的步骤

步骤1)要使用Python创建压缩文件,请确保您的导入语句正确,并且顺序正确。 导入语句是 from shutil import make_archive

代码说明

  • from shutil import make_archive 导入make_archive 类
  • 使用split函数从src中分离出目录和文件名
  • 然后我们调用模块“ shutil.make_archive(“ guru99 archive,” zip“,root_dir)”创建压缩文件,该文件将采用zip格式进行压缩
  • 我们传递了目录root_dir,这个目录所有内容都将被压缩
  • 运行代码时,您可以看到创建了压缩的zip文件 guru99 archive.zip。

步骤2)

您可以右键单击该文件并选择"show in explorer"

它将在文件浏览器显示您的压缩文件,如下所示。

步骤3)当您双击文件时,您将看到列表中的所有文件。

步骤4)我们可以定义要包含在压缩存档中的特定文件,可以更好地控制如何进行压缩的过程。 修改代码如下,我们将在压缩存档中只包含这两个文件“ guru.txt”和“ guru.txt.bak”。

代码说明

  • 从zipfile模块导入ZipFile类。
  • 我们创建一个新的Zipfile( "testguru99.zip, "w")
  • 创建一个新的Zipfile类需要传递权限,这里使用"w"表示写权限
  • 我们使用变量“ newzip”来引用我们创建的zip文件
  • 使用“ newzip”变量上的write函数,我们将文件“ guru.txt”和“ guru.txt.bak”添加到压缩文件中

注意:在这里,由于使用了“ With”作用域锁,因此我们没有给出任何命令来“close”文件,例如“ newzip.close”,当程序超出此作用域时,该文件将被清理并自动关闭。

步骤5)当您->右键单击文件(testguru.zip)并->选择操作系统(Windows资源管理器)时,它将在文件夹中显示存档文件,如下所示。

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

这是完整的代码

Python 2 Example

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("guru.txt"):
# get the path to the file in the current directory
	src = path.realpath("guru.txt");
# rename the original file
	os.rename("career.guru.txt","guru.txt")
# now put things into a ZIP archive
	root_dir,tail = path.split(src)
    shutil.make_archive("guru archive", "zip", root_dir)
# more fine-grained control over ZIP files
	with ZipFile("testguru.zip","w") as newzip:
	newzip.write("guru.txt")
	    newzip.write("guru.txt.bak")
if __name__== "__main__":
	  main()

Python 3 Example

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

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

摘要

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

最近发表
标签列表