Compress and Save File as Zip

  • Share this:

Code introduction


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


Technology Stack : os, zipfile

Code Type : Function

Code Difficulty : Intermediate


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

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

    return output_path                
              
Tags: