Compress File to ZIP and Return Details

  • Share this:

Code introduction


This function compresses the specified file into a zip format and returns the name of the generated zip file and the file modification time.


Technology Stack : os, zipfile, datetime

Code Type : File compression

Code Difficulty : Intermediate


                
                    
def zip_file(file_path):
    import os
    import zipfile
    from datetime import datetime

    # 创建一个zip文件
    zip_name = f"{os.path.basename(file_path)}.zip"
    with zipfile.ZipFile(zip_name, 'w') as zipf:
        zipf.write(file_path, arcname=os.path.basename(file_path))

    # 获取文件修改时间
    file_mod_time = datetime.fromtimestamp(os.path.getmtime(file_path)).strftime('%Y-%m-%d %H:%M:%S')

    return zip_name, file_mod_time