James
James

Reputation: 31738

How to unzip specific folder from a .zip with Python

I am looking to unzip a particular folder from a .zip in Python:

e.g. archive.zip contains the folders foo and bar, I want to unzip foo to a specific location, retaining it's folder structure.

Upvotes: 30

Views: 37484

Answers (4)

You should close your zips....


import zipfile

archive = zipfile.ZipFile('archive.zip')

for file in archive.namelist():
    if file.startswith('foo/'):
        archive.extract(file, 'destination_path')

archive.close()

Or just use a safer method. With will close your zip.

import zipfile
with zipfile.ZipFile('archive.zip') as archive:
    for file in archive.namelist():
        if file.startswith('foo/'):
            archive.extract(file, 'destination_path')

Upvotes: 3

Andrew Garcia
Andrew Garcia

Reputation: 91

I like to reduce the list of names first so that the for loop doesn't parse through all the files in the zip archive:

import zipfile

archive = zipfile.ZipFile('archive.zip')

names_foo = [i for i in archive.namelist() if i.startswith('foo') ]

for file in names_foo:
    archive.extract(file)

Upvotes: 2

Sajjad Aemmi
Sajjad Aemmi

Reputation: 2607

using zipfile library is very very slow. this is better way:

os.system('unzip -P your-password path/to/file.zip')

Upvotes: -2

kaspersky
kaspersky

Reputation: 4097

Check zipfile module.

For your case:

import zipfile

archive = zipfile.ZipFile('archive.zip')

for file in archive.namelist():
    if file.startswith('foo/'):
        archive.extract(file, 'destination_path')

Upvotes: 45

Related Questions