2013-10-27 79 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文件名作爲命令行上的第一個參數(對於這個例子)。如果這不是您想使用它的方式,請將其更改爲從需要的任何位置獲取文件名。 –