Pyzipper解压文件和压缩文件夹


Pyzipper解压文件和压缩文件夹方法


要使用Python的pyzipper库来压缩文件夹并添加密码,你可以按照以下步骤进行:

首先,确保你已经安装了pyzipper库。你可以使用pip进行安装:

pip install pyzipper

Pyzipper解压文件和压缩文件夹方法如下:

import os

import pyzipper


class ZipTools:

    @staticmethod    def extract_zip(zip_file, extract_folder, password):
        with pyzipper.AESZipFile(zip_file) as z:
            try:
                z.extractall(extract_folder, pwd=password.encode('utf-8'))
                print(f"Successfully extracted {zip_file} to {extract_folder}")
            except Exception as e:
                print(f"Extraction failed: {e}")

    @staticmethod    def zip_folder(folder_path, zip_path, password):
        with pyzipper.AESZipFile(zip_path, 'w', compression=pyzipper.ZIP_DEFLATED, encryption=pyzipper.WZ_AES) as zf:
            # 将密码转换为字节类型            password_bytes = password.encode('utf-8')
            zf.setpassword(password_bytes)
            for root, dirs, files in os.walk(folder_path):
                for file in files:
                    abs_path = os.path.join(root, file)
                    rel_path = os.path.relpath(abs_path, os.path.dirname(folder_path))
                    zf.write(abs_path, rel_path)
if __name__ == "__main__":
    folder_to_zip = 'D:/App/Log'    zip_file_path = 'D:/App/Log.zip'    password = '123123'    ZipTools.zip_folder(folder_to_zip, zip_file_path, password)

Pyzipper解压文件和压缩文件夹方法


要使用Python的pyzipper库来压缩文件夹并添加密码,你可以按照以下步骤进行:

首先,确保你已经安装了pyzipper库。你可以使用pip进行安装:

pip install pyzipper

Pyzipper解压文件和压缩文件夹方法如下:

import os

import pyzipper


class ZipTools:

    @staticmethod    def extract_zip(zip_file, extract_folder, password):
        with pyzipper.AESZipFile(zip_file) as z:
            try:
                z.extractall(extract_folder, pwd=password.encode('utf-8'))
                print(f"Successfully extracted {zip_file} to {extract_folder}")
            except Exception as e:
                print(f"Extraction failed: {e}")

    @staticmethod    def zip_folder(folder_path, zip_path, password):
        with pyzipper.AESZipFile(zip_path, 'w', compression=pyzipper.ZIP_DEFLATED, encryption=pyzipper.WZ_AES) as zf:
            # 将密码转换为字节类型            password_bytes = password.encode('utf-8')
            zf.setpassword(password_bytes)
            for root, dirs, files in os.walk(folder_path):
                for file in files:
                    abs_path = os.path.join(root, file)
                    rel_path = os.path.relpath(abs_path, os.path.dirname(folder_path))
                    zf.write(abs_path, rel_path)
if __name__ == "__main__":
    folder_to_zip = 'D:/App/Log'    zip_file_path = 'D:/App/Log.zip'    password = '123123'    ZipTools.zip_folder(folder_to_zip, zip_file_path, password)

打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在