Compress Files with Specific Pattern into Zip File

  • Share this:

Code introduction


This function is used to compress files in a specified directory (matching a specific pattern) into a zip file.


Technology Stack : os, zipfile, pathlib

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_file(directory, file_pattern, output_zip):
    import os
    import zipfile
    from pathlib import Path

    # 首先检查目录是否存在
    if not os.path.exists(directory):
        print(f"Directory {directory} does not exist.")
        return

    # 创建zip文件
    with zipfile.ZipFile(output_zip, 'w') as zipf:
        # 遍历目录
        for root, dirs, files in os.walk(directory):
            for file in files:
                if file.endswith(file_pattern):
                    # 构建完整的文件路径
                    file_path = os.path.join(root, file)
                    # 将文件添加到zip文件中
                    zipf.write(file_path, arcname=os.path.relpath(file_path, directory))

    print(f"Zip file {output_zip} created successfully.")