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

使用Python的zipfile()模块解密加密的ZIP文件

发布时间:2023-12-30 13:54:48

Python的zipfile模块提供了对ZIP文件的创建、读取和解压缩的支持。它也提供了对ZIP文件内的文件进行加密和解密的功能。在本文中,我们将介绍如何使用zipfile模块来解密和加密ZIP文件,并提供相关的示例。

首先,我们来看一下如何使用zipfile模块来解密一个加密的ZIP文件。

要解密一个ZIP文件,我们需要使用ZipFile类的setpassword()方法来设置密码。然后,可以使用extractall()方法将ZIP文件解压缩到指定的目录。

下面是一个解密ZIP文件的示例:

import zipfile

def decrypt_zip_file(zip_file, password, extract_dir):
    with zipfile.ZipFile(zip_file) as zf:
        zf.extractall(path=extract_dir, pwd=password.encode())

# 要解密的ZIP文件
encrypted_zip_file = 'encrypted.zip'

# 解密密码
password = 'password123'

# 解压缩目录
extract_dir = 'extracted_files'

decrypt_zip_file(encrypted_zip_file, password, extract_dir)

在上面的示例中,decrypt_zip_file()函数接受三个参数:待解密的ZIP文件、密码和解压缩目录。它使用with语句来打开ZIP文件,并使用setpassword()方法设置密码。然后,使用extractall()方法解压缩ZIP文件到指定的目录。

下面是一个使用zipfile模块加密ZIP文件的示例:

import zipfile

def encrypt_zip_file(zip_file, password, files):
    with zipfile.ZipFile(zip_file, 'w', zipfile.ZIP_DEFLATED) as zf:
        zf.setpassword(password.encode())
        for file in files:
            zf.write(file)

# 要加密的文件列表
files_to_encrypt = ['file1.txt', 'file2.txt']

# 加密后的ZIP文件名
encrypted_zip_file = 'encrypted.zip'

# 加密密码
password = 'password123'

encrypt_zip_file(encrypted_zip_file, password, files_to_encrypt)

在上面的示例中,encrypt_zip_file()函数接受三个参数:加密后的ZIP文件名、密码和要加密的文件列表。它使用with语句来创建一个ZIP文件,并使用setpassword()方法设置密码。然后,使用write()方法将文件添加到ZIP文件中,并最后关闭ZIP文件。

以上是使用Python的zipfile模块解密和加密ZIP文件的简单示例。根据实际需求,您可以进一步修改和扩展这些示例以适应您的需求。