Compress and Timestamp File into Zip

  • Share this:

Code introduction


This function compresses a specified file into a zip format and adds the creation time of the file to the compressed file.


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

    # Check if file exists
    if not os.path.isfile(file_path):
        raise FileNotFoundError(f"The file {file_path} does not exist.")

    # Create a zipfile
    with zipfile.ZipFile(output_path, 'w') as zipf:
        zipf.write(file_path, os.path.basename(file_path))

    # Add metadata to the zipfile
    zipf.write(f"{os.path.basename(file_path)}.txt", f"{os.path.basename(file_path)}.txt")
    with open(f"{os.path.basename(file_path)}.txt", "w") as text_file:
        text_file.write(f"File name: {os.path.basename(file_path)}\n")
        text_file.write(f"Created on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")

    return output_path