abbazs
Posted on February 18, 2021
Tutorial: Extracting Zip Files
In this tutorial, we will learn how to extract all the Zip files in a directory using Python's zipfile
module and the pathlib
module. We'll go through the code step by step and discuss different ways to encapsulate this functionality in a function.
Code Explanation
import zipfile
from pathlib import Path
# Set the target directory
p = Path('.')
# Iterate over all Zip files in the directory
for f in p.glob('*.zip'):
# Open the Zip file
with zipfile.ZipFile(f, 'r') as archive:
# Extract all contents of the Zip file to a directory with the same name as the file
archive.extractall(path=f'./{f.stem}')
# Print a message indicating that the extraction is complete
print(f"Extracted contents from '{f.name}' to '{f.stem}' directory.")
The code performs the following steps:
Import the necessary modules:
zipfile
for working with Zip files andpathlib
for working with file paths.Create a
Path
object to represent the current directory. You can modify this to specify a different directory if needed.Use the
glob
method of thePath
object to iterate over all the Zip files (*.zip
) in the current directory.For each Zip file, open it using
zipfile.ZipFile
in read mode ('r'
).Use the
extractall
method of the Zip file object to extract all the contents of the Zip file to a directory with the same name as the file. Thepath=f'./{f.stem}'
argument specifies the destination directory.After the extraction is complete, print a message indicating that the process is done, using
print(f"Extracted contents from '{f.name}' to '{f.stem}' directory.")
.
Recipe 1: Function with Directory Parameter
import zipfile
from pathlib import Path
def extract_zip_files(directory):
p = Path(directory)
for f in p.glob('*.zip'):
with zipfile.ZipFile(f, 'r') as archive:
archive.extractall(path=f'./{f.stem}')
print(f"Extracted contents from '{f.name}' to '{f.stem}' directory.")
# Usage example
extract_zip_files('.')
This recipe demonstrates creating a function extract_zip_files
that accepts a directory
parameter. It performs the same functionality as the previous code but allows you to specify a different directory.
Recipe 2: Function with Output Path
import zipfile
from pathlib import Path
def extract_zip_files(directory, output_path):
p = Path(directory)
for f in p.glob('*.zip'):
with zipfile.ZipFile(f, 'r') as archive:
archive.extractall(path=output_path)
print(f"Extracted contents from '{f.name}' to '{output_path}' directory.")
# Usage example
extract_zip_files('.', './extracted_files')
This recipe demonstrates creating a function extract_zip_files
that accepts both a directory
parameter and an output_path
parameter. It allows you to specify a custom output directory where the extracted files will be stored.
Posted on February 18, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.