Compress and Timestamp File Addition

  • Share this:

Code introduction


This function compresses a file at the specified path and saves it to the output path, while also recording the time when the file was added.


Technology Stack : os, zipfile, datetime

Code Type : File compression

Code Difficulty : Intermediate


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

    def file_date(file_path):
        return datetime.fromtimestamp(os.path.getmtime(file_path)).strftime('%Y-%m-%d %H:%M:%S')

    try:
        with zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
            zipf.write(file_path)
        return f"File {file_path} added to {output_path} at {file_date(output_path)}"
    except Exception as e:
        return f"Failed to add file: {e}"