用python的ZipFile库解压会得到一个奇怪的结果

2024-06-16 15:04:20 发布

您现在位置:Python中文网/ 问答频道 /正文

给定一个zip文件和pythonzipfile库,我在提取时体验到一个奇怪的输出:位于归档文件根目录的文件被解压到一个名为归档名的子目录中。在

以下是我使用ZipFile库的方法:

#!/usr/bin/X11/python

import sys
import urllib
import zipfile
import os.path
import os
import tempfile

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

try:
    # Get the latest release
    print 'Downloading stack archive...'
    (vagrantstack, infoheaders) = urllib.urlretrieve ('https://github.com/jquery/globalize/archive/master.zip')

    # Unzip in the project folder
    print 'Unzipping...'
    unzip(vagrantstack, '.')

finally:
    urllib.urlcleanup()

这应该复制jquery/globalize存储库的确切结构,但是所有根文件都放在一个子目录中。。。在

有人能指出这里的问题吗?在

免责声明:解压功能本身不是我的,但在我看来是正确的。在

编辑:以下是我得到的输出:

^{pr2}$

globalize master/globalize master文件夹不应存在,其内容应位于根目录下。在


Tags: 文件pathinimportmasterosurllibzip
2条回答

您试图下载的存档文件没有顶级文件。 归档文件由一个名为globalize-master的目录组成,该目录包含所有文件,因此您看到的行为是正确的。在

如果使用unzip提取内容,您将看到相同的行为:

$ls
globalize-master.zip
$unzip globalize-master.zip 
Archive:  globalize-master.zip
300a9dc6cb4a08eb847c8565ee01eae4cd9aa35c
   creating: globalize-master/
 extracting: globalize-master/.bowerrc  
  [...]
  inflating: globalize-master/test/util.js  
$ls -l
totale 116
drwxrwxr-x 5 username username   4096 lug 13 07:35 globalize-master
-rw-r r  1 username username 113313 lug 21 12:44 globalize-master.zip

从源代码中可以很清楚地看到,unzip函数对文件名所做的一切都是无用的,因为它已经由ZipFile.extract处理。 unzip的正确版本是:

^{pr2}$

从而产生预期的产出。在

请注意,这相当于使用^{}方法:

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

肯定是unzip()中的某个问题。它在所有目录中创建一个globalize-master子目录,而不仅仅是根目录。在

如果您信任zip文件源,则可以使用zf.extractall(dest_dir)^{}对于python2.7.4和更高版本应该是安全的。在

相关问题 更多 >