0
0
PythonHow-ToBeginner · 3 min read

How to Add Files to Zip in Python Easily

Use Python's zipfile module to add files to a zip archive. Open a zip file in write or append mode with zipfile.ZipFile, then use .write() to add files.
📐

Syntax

To add files to a zip archive, use the zipfile.ZipFile class with modes 'w' (write) or 'a' (append). Then call .write(filename, arcname=None) to add each file.

  • filename: Path of the file to add.
  • arcname: Optional name inside the zip.
python
import zipfile

with zipfile.ZipFile('archive.zip', mode='w') as zf:
    zf.write('file1.txt')  # Add file1.txt to archive.zip
    zf.write('file2.txt', arcname='docs/file2.txt')  # Add with new name/path inside zip
💻

Example

This example creates a zip file named example.zip and adds two text files to it. It shows how to open the zip in write mode and add files with .write().

python
import zipfile

# Create example files
with open('hello.txt', 'w') as f:
    f.write('Hello, world!')

with open('readme.txt', 'w') as f:
    f.write('This is a readme file.')

# Add files to zip
with zipfile.ZipFile('example.zip', mode='w') as zf:
    zf.write('hello.txt')
    zf.write('readme.txt', arcname='docs/readme.txt')

print('Files added to example.zip')
Output
Files added to example.zip
⚠️

Common Pitfalls

Common mistakes include:

  • Using mode 'w' which overwrites existing zip files instead of 'a' to append.
  • Not closing the zip file, which can corrupt it. Use with to auto-close.
  • Adding files with wrong paths or missing files causing errors.
python
import zipfile

# Wrong: overwrites existing zip and loses previous files
with zipfile.ZipFile('archive.zip', mode='w') as zf:
    zf.write('file1.txt')

# Right: append to existing zip without losing files
with zipfile.ZipFile('archive.zip', mode='a') as zf:
    zf.write('file2.txt')
📊

Quick Reference

MethodDescription
zipfile.ZipFile(filename, mode)Open a zip file in 'w' (write), 'a' (append), or 'r' (read) mode
.write(filename, arcname=None)Add a file to the zip archive, optionally renaming inside zip
.close()Close the zip file (auto with 'with' statement)

Key Takeaways

Use the zipfile module's ZipFile class to add files to zip archives.
Open the zip file in 'w' mode to create or overwrite, 'a' mode to add without deleting existing files.
Use the .write() method to add each file, optionally renaming it inside the zip.
Always use a with statement to ensure the zip file closes properly.
Check file paths carefully to avoid errors when adding files.