1 min read

Python Zipfile Module

The zipfile module allows you to create, read, write, append, and list a ZIP file.

Importing the Module

import zipfile

Reading ZIP Files

To read a ZIP file, you can use the zipfile.ZipFile class in read mode ('r').

Listing Files

The namelist() method returns a list of archive members by name.

import zipfile

with zipfile.ZipFile('example.zip', 'r') as zip_ref:
    print(zip_ref.namelist())

Extracting Files

  • extractall(): Extracts all members from the archive to the current working directory or a specified directory.
  • extract(): Extracts a single member.
import zipfile

with zipfile.ZipFile('example.zip', 'r') as zip_ref:
    zip_ref.extractall('extracted_files')

Writing to ZIP Files

To write to a ZIP file, open it in write mode ('w'). Note that this will erase the existing file. To append, use append mode ('a').

You can also specify the compression method (e.g., zipfile.ZIP_DEFLATED).

import zipfile

with zipfile.ZipFile('new_archive.zip', 'w', zipfile.ZIP_DEFLATED) as zip_ref:
    zip_ref.write('file_to_compress.txt')

programming/python/python