解压缩并重命名zip文件夹

mac*_*ace 1 python directory zip extract

我想从python中提取一个zip文件中的特定文件夹,然后在原始文件名后重命名它.

例如,我有一个名为test.zip包含多个文件夹和子文件夹的文件:

xl/media/image1.png
xl/drawings/stuff.png
stuff/otherstuff.png
Run Code Online (Sandbox Code Playgroud)

我希望将提取的媒体文件夹的内容提供给名为test的文件夹: test/image1.png

Luk*_*raf 7

使用

例如:

#!/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)
Run Code Online (Sandbox Code Playgroud)

使用try..except块来处理创建目录,删除文件和解压缩时可能发生的各种异常.