Reputation: 31738
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
Reputation: 169
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
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
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