2012-10-15 37 views
0

我正試圖用Python解壓縮文件。我使用下面的函數:ZipFile不能提取目錄中的壓縮文件

def unzip(source_filename, dest_dir): 
    zf = zipfile.ZipFile(source_filename) 
    for member in zf.infolist(): 
     # Path traversal defense copied from 
     # http://hg.python.org/cpython/file/tip/Lib/http/server.py#l789 
     words = filter(None, 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) 

當解壓與目錄的.zip稱爲「鬼」,我得到以下錯誤:

Traceback (most recent call last): 
    File "MCManager.py", line 137, in add 
    unzip(addedFilepath, dirUnzipped) 
    File "MCManager.py", line 19, in unzip 
    zf.extract(member, path) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/zipfile.py", line 928, in extract 
    File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/zipfile.py", line 962, in _extract_member 
    File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/os.py", line 157, in makedirs 
OSError: [Errno 20] Not a directory: '/Users/student/Library/Application Support/minecraft/temp/unzipped/gui/gui' 

這是一個問題的ZipFile()?

+0

是否存在'/ Users/student/Library/Application Support/minecraft/temp/unzipped/gui'?如果是,是'/ Users/student/Library/Application Support/minecraft/temp/unzipped/gui/gui'目錄嗎? – nneonneo

+0

@nneonneo事實證明,當我用普通的zip實用工具解壓縮它時,「gui」是一個帶有.png的目錄,但是我的腳本創建了一個帶有該名稱的空文件。 – tkbx

+0

是的,似乎任何時候zip包含一個目錄,我得到這個錯誤。 – tkbx

回答

0

檢查documentation的方法extract,你會發現,這是由你的方法通過可變dest_dir收到path變量必須的路徑,要被提取你迭代的zip文件的內容目錄至。

正如你所指出的問題,gui是一個文件,而不是一個目錄。說實話,你的說法

When unzipping a .zip with a file called "gui (...)"

沒有什麼意義。

此外,您可能需要查看os.mkdir方法,以便您可以按需創建目錄。

+0

我正在給函數提供一個.zip文件的路徑,以及一個不存在的目錄,它似乎正常創建。不知道你的意思是「沒什麼意義」,但我的意思是.zip文件在解壓縮時會創建一個名爲「gui」的文件,但我現在知道它是一個目錄,然後用一個普通實用工具解壓縮。 – tkbx

+0

好的,所以我測試了你的代碼,它成功地解壓縮了一個zip文件。您能否告訴我們您正在運行腳本的目錄以及您傳遞給解壓縮方法的參數?謝謝! – arturhoo

+0

做了zip包含一個目錄? – tkbx

相關問題