0

我正在尝试用 Python 解压缩文件。我正在使用以下功能:

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)

使用名为“gui”的目录解压缩 .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() 的问题吗?

4

1 回答 1

0

检查方法的文档extract,您会发现path您的方法通过变量接收的变量dest_dir必须是您希望将迭代的 zip 文件的内容提取到的目录的路径。

正如您在问题中所述,gui是文件,而不是目录。老实说,你声明

使用名为“gui (...)”的文件解压缩 .zip 时

没有多大意义。

此外,您可能想查看该os.mkdir方法,以便您可以按需创建目录。

于 2012-10-15T13:54:41.770 回答