Compress File into Zip Format

  • Share this:

Code introduction


This function takes two arguments: one is the file path (file_path), and the other is the output path (output_path). The function's purpose is to compress the specified file into a zip format and save it at the output path. If the output path already exists, it will be overwritten.


Technology Stack : os, zipfile

Code Type : Function

Code Difficulty :


                
                    
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)

    print(f"File '{file_path}' has been added to '{output_path}'")                
              
Tags: