2013-10-20 36 views
8

我正嘗試使用此處找到的代碼提取壓縮文件夾。Python zipfile.extract()不會提取所有文件

def unzip(source_filename, dest_dir): 
with zipfile.ZipFile(source_filename) as zf: 

    for member in zf.infolist(): 
     words = member.filename.split('/') 
     path = dest_dir 
     for word in words[:-1]: 
      drive, word = os.path.splitdrive(word) 
      head, word = os.path.split(word) 
      if word in (os.curdir, os.pardir, ''): continue 
      path = os.path.join(path, word) 
     zf.extract(member, path) 

但試圖提取時,例如,wordpress.zip與目錄結構
的wordpress/
-wp內容/
--- somefile.php
-wp-config.php文件
-index.php
我只獲取根文件夾或wordpress /下的文件夾中的文件。所以我得到wordpress/wp-content/somefile.php而不是wordpress /文件夾本身的文件。

回答

14

看的第一個地方是the documentation

ZipFile.extractall([path[, members[, pwd]]]) 

將其應用於您的情況,我想嘗試:

def unzip(source_filename, dest_dir): 
    with zipfile.ZipFile(source_filename) as zf: 
     zf.extractall(dest_dir) 
+0

這個工作,但我輸路徑遍歷保護。謝謝。 –

+1

它看起來像2.7.4和更高版本中存在的保護。 –

相關問題