Extract a Single Member from a ZIP Archive in Python

Extract one specific file from a ZIP archive to an output directory using the standard zipfile and pathlib modules.

Easy Python 3.9+ Aug 9, 2026 Files & data 19 views 0 copies

Python code

21 lines
Python 3.9+
import zipfile
from pathlib import Path

def extract_single_member(zip_path: str, member_name: str, output_dir: str = ".") -> Path:
    """Extract a single member from a zip archive to the output directory."""
    with zipfile.ZipFile(zip_path, "r") as archive:
        archive.extract(member_name, output_dir)
    return Path(output_dir) / member_name

if __name__ == "__main__":
    zip_path = "sample.zip"
    member_name = "important_data.txt"
    
    # Create a sample zip file for demonstration
    with zipfile.ZipFile(zip_path, "w") as archive:
        archive.writestr("important_data.txt", "Hello, world!")
        archive.writestr("other_file.txt", "Not extracted")
    
    extracted_path = extract_single_member(zip_path, member_name)
    print(f"Extracted: {extracted_path}")
    print(f"Contents: {extracted_path.read_text()}")

Output

stdout
Extracted: important_data.txt
Contents: Hello, world!

How it works

The zipfile.ZipFile context manager opens the ZIP archive for reading. Calling archive.extract(member_name, output_dir) pulls out just the named file and writes it under the target directory. Using Path from pathlib lets us build the final path cleanly and read back the contents. The sample code writes a temporary ZIP so the example runs anywhere, then extracts only important_data.txt and prints its text.

Common mistakes

  • Passing a path with subdirectories as member_name without ensuring the output directory tree exists.
  • Forgetting that member names are case-sensitive and must exactly match the archive entry.
  • Using `extractall` when you only need one file, which can waste time and write extra files.

Variations

  1. Read the file content in memory with `archive.read(member_name)` instead of writing to disk.
  2. Use `zipfile.Path` from the third-party `zipp` backport for a pathlib-style interface to the archive.

Real-world use cases

  • Downloading a single log file from a large report bundle without unpacking everything to disk.
  • Extracting just the newest config or data file from a daily archive in a scheduled job.
  • Pulling one artifact out of a deployment package to verify or hot-patch it in production.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.