Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract and rename zip file folder

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

like image 755
mace Avatar asked Jan 19 '26 05:01

mace


1 Answers

Use

  • the zipfile module, particularly ZipFile.extractall()
  • os.path.splitext() to get test1 from the string test1.zip
  • tmpfile.mkdtemp() to create a temporary directory
  • shutil.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.

like image 105
Lukas Graf Avatar answered Jan 20 '26 20:01

Lukas Graf