Compress File to ZIP Format

  • Share this:

Code introduction


This function compresses a file at a specified path into a zip format and saves it to a specified output path.


Technology Stack : os, zipfile

Code Type : File processing

Code Difficulty : Intermediate


                
                    
def zip_file(file_path, output_path):
    import os
    import zipfile

    # 检查文件是否存在
    if not os.path.exists(file_path):
        raise FileNotFoundError(f"The file {file_path} does not exist.")

    # 创建一个zip文件
    with zipfile.ZipFile(output_path, 'w') as zipf:
        zipf.write(file_path, os.path.basename(file_path))

    return output_path                
              
Tags: