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.
Python code
21 linesimport 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
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
- Read the file content in memory with `archive.read(member_name)` instead of writing to disk.
- 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
More from Files & data
- Append a Line to a Log File in Python easy
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a File Index by Relative Path Hash Map in Python easy
Keep learning
Related tutorials and quizzes for this topic.