2 years ago

#39933

test-img

KZiovas

How to find and unzip all the .zip archives in a directory with Python?

I wish to scan a directory with Python make a list with the names of all the .zip archives in the directory and then extract those zip archives to a different directory.

For example I have a downloads directory and a unpacked directory. The downloads directory contains a data_002.zip and measurements-033.zip archive and other folders and files. Whats the best way to extract both of these archives in the unpacked directory?

I scan all the contents of the downloads directory looking for a .zip ending and then extract them like :

import os
from os import path
from pathlib import Path

archives = []
for content in os.listdir("downloads"):
    if file.endswith(".zip"):
        archives.append(path.join("downloads",content))

for archive in archives:
    with zipfile.ZipFile(archive, "r") as extractor:
                file_stem = Path(path.basename(archive)).stem  # Remove the .zip ending
                unpacked_path = path.join("unpacked", file_stem)
                extractor.extractall(unpacked_path)

Is there a better way to find and extract these archives ? Specifically what I am looking for is a better way to search for these zip files instead of looking thought the listdir results for a .zip ending.

python

zip

unzip

0 Answers

Your Answer

Accepted video resources