给定一个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文件夹不应存在,其内容应位于根目录下。在
您试图下载的存档文件没有顶级文件。 归档文件由一个名为
globalize-master
的目录组成,该目录包含所有文件,因此您看到的行为是正确的。在如果使用
unzip
提取内容,您将看到相同的行为:从源代码中可以很清楚地看到,
^{pr2}$unzip
函数对文件名所做的一切都是无用的,因为它已经由ZipFile.extract
处理。unzip
的正确版本是:从而产生预期的产出。在
请注意,这相当于使用^{} 方法:
肯定是
unzip()
中的某个问题。它在所有目录中创建一个globalize-master
子目录,而不仅仅是根目录。在如果您信任zip文件源,则可以使用} 对于python2.7.4和更高版本应该是安全的。在
zf.extractall(dest_dir)
。^{相关问题 更多 >
编程相关推荐