Compress File to Zip Format

  • Share this:

Code introduction


This function takes a file path and an output path, compresses the specified file into a zip format and saves it to the output path.


Technology Stack : zipfile, os

Code Type : Function

Code Difficulty : Intermediate


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

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

    return output_path                
              
Tags: