Reputation: 508
I would like to extract in python a specific folder from a zip file and then rename it after the original file name.
For example I have a file called test.zip
containing several folders and subfolders:
xl/media/image1.png
xl/drawings/stuff.png
stuff/otherstuff.png
I want the content of the media folder extracted to a folder called test:
test/image1.png
Upvotes: 2
Views: 8947
Reputation: 32650
Use
zipfile
module, particularly ZipFile.extractall()
os.path.splitext()
to get test1
from the string test1.zip
tmpfile.mkdtemp()
to create a temporary directoryshutil.move()
to move entire directory trees.For example:
#!/usr/bin/env python
"""Usage:
./extract.py test.zip
"""
from zipfile import ZipFile
import os
import sys
import tempfile
import shutil
ROOT_PATH = 'xl/media/'
zip_name = sys.argv[1]
zip_path = os.path.abspath(zip_name)
extraction_dir = os.path.join(os.getcwd(), os.path.splitext(zip_name)[0])
temp_dir = tempfile.mkdtemp()
with ZipFile(zip_path, 'r') as zip_file:
# Build a list of only the members below ROOT_PATH
members = zip_file.namelist()
members_to_extract = [m for m in members if m.startswith(ROOT_PATH)]
# Extract only those members to the temp directory
zip_file.extractall(temp_dir, members_to_extract)
# Move the extracted ROOT_PATH directory to its final location
shutil.move(os.path.join(temp_dir, ROOT_PATH), extraction_dir)
# Uncomment if you want to delete the original zip file
# os.remove(zip_path)
print "Sucessfully extracted '%s' to '%s'" % (zip_path, extraction_dir)
Use try..except
blocks to deal with the various exceptions that can happen when creating directories, removing files and extracting the zip.
Upvotes: 9