Create and Compress Directory into Zip File

  • Share this:

Code introduction


This function compresses the files and folders in a specified directory into a zip file. If the output path already exists, it will delete the files and folders in the path and recreate the zip file.


Technology Stack : os, zipfile, shutil

Code Type : File compression

Code Difficulty : Intermediate


                
                    
def zip_file(file_path, output_path):
    import os
    import zipfile
    from shutil import rmtree

    # 创建一个zip文件
    with zipfile.ZipFile(output_path, 'w') as zipf:
        # 遍历文件路径,添加到zip文件中
        for foldername, subfolders, filenames in os.walk(file_path):
            for filename in filenames:
                filepath = os.path.join(foldername, filename)
                zipf.write(filepath, os.path.relpath(filepath, file_path))

    # 检查zip文件是否创建成功
    if os.path.exists(output_path):
        print(f"Zip file created successfully: {output_path}")
    else:
        print("Failed to create zip file.")                
              
Tags: