[Python] Compressing and Creating ZIP Files: Writing and Appending with zipfile

The Python standard library zipfile module allows you to group existing files to create a ZIP archive or add new files to an existing ZIP file.

A key point to note is that by default, “compression” is not performed; files are simply bundled (stored) without compression. To reduce file size, you must explicitly specify a compression method.

This article explains how to compress and archive project document files into ZIP format.

目次

1. Creating a New ZIP File (‘w’ mode)

Create a ZipFile object in "w" (Write) mode and use the write() method to add files. By specifying compression=zipfile.ZIP_DEFLATED, the files will be compressed using the standard Deflate method.

Source Code

import zipfile
import os

# List of files to compress
# (Ensure these files exist in your directory before running)
files_to_compress = ["project_plan.pdf", "budget_sheet.xlsx", "meeting_notes.txt"]

# Name of the ZIP file to create
archive_name = "project_archive.zip"

print(f"--- Creating ZIP file '{archive_name}' ---")

# 1. Create ZipFile object in write mode ('w')
# If compression=zipfile.ZIP_DEFLATED is not specified, file size won't decrease
with zipfile.ZipFile(archive_name, "w", compression=zipfile.ZIP_DEFLATED) as zf:
    
    for filename in files_to_compress:
        # Check if file exists to avoid errors in this example
        if os.path.exists(filename):
            # 2. Write using write(file_path, [archive_name_inside_zip])
            zf.write(filename)
            print(f"Adding: {filename}")
        else:
            print(f"Warning: File '{filename}' not found. Skipping.")

print("Compression complete.")

2. Appending to an Existing ZIP File (‘a’ mode)

If you want to add another file to an existing ZIP file later, open it in "a" (Append) mode. Be careful: if you accidentally open it in "w" mode, the existing contents will be erased.

Source Code

import zipfile
import os

archive_name = "project_archive.zip"
additional_file = "additional_image.png"

print(f"--- Adding file to '{archive_name}' ---")

# Open in append mode ('a')
with zipfile.ZipFile(archive_name, "a", compression=zipfile.ZIP_DEFLATED) as zf:
    
    if os.path.exists(additional_file):
        # Add the file
        # Using the arcname argument allows you to rename the file inside the ZIP
        # Example: Storing it as "images/added_image.png"
        zf.write(additional_file, arcname="images/added_image.png")
        print(f"Append complete: {additional_file}")
    else:
        print(f"Warning: File '{additional_file}' not found.")

Explanation

Distinguishing Modes

  • “w” (Write): Create new. If a file with the same name exists, it is overwritten (contents are emptied).
  • “a” (Append): Append. If the ZIP file exists, files are added to the end. If it does not exist, a new one is created.

Controlling File Names (arcname)

If you use the write(filename) method as is, the specified path structure might be recorded in the ZIP (e.g., C:\Users\Name\Docs\file.txt).

If you want to store just the filename or place it in a specific folder inside the ZIP, use the second argument, arcname.

# Example: The actual file is "data/2025/log.txt", 
# but it is placed at the root as "log.txt" inside the ZIP
zf.write("data/2025/log.txt", arcname="log.txt")
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次