2013-10-27 84 views
1

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

比如我有一个名为包含几个文件夹和子文件夹test.zip

xl/media/image1.png 
xl/drawings/stuff.png 
stuff/otherstuff.png 

我想提取到一个文件夹名为test的媒体文件夹的内容: test/image1.png

+3

样板问题:你到目前为止试过了什么?在问题中提到它是否有。 –

回答

5

使用

例如:

#!/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) 

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

+0

谢谢,这个工程,当我指定zip_name ='test.zip'但与sys.argv [1]我得到一个错误:列表索引超出范围 – mace

+0

请参阅**使用**在文件的顶部。你应该给zip文件名作为命令行上的第一个参数(对于这个例子)。如果这不是您想使用它的方式,请将其更改为从需要的任何位置获取文件名。 –