0

我正在使用下面的代码来提取文件,如下所示,但我看到正在创建额外的文件夹,有人可以帮助我为什么要创建额外的文件夹。

我的文件是 abc.zip,其中包含文件 sql.db,所以理想情况下我需要文件夹文件作为 abc/sql.db 但是当我使用下面的代码提取时,我得到的文件夹是 acb/abc/sql.db,为什么我得到这个正在创建额外的文件夹

def unzip_artifact( local_directory, file_path ):
    fileName, ext = os.path.splitext( file_path )
    if ext == ".zip":
        print 'unzipping file ' + basename(fileName) + ext
        try:
            with zipfile.ZipFile(file_path) 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 = local_directory
                        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)

        except zipfile.error, e:
            print "Bad zipfile: %s" % (e)
        return
4

1 回答 1

0

通常解压缩文件将为您创建目录。因此,如果 .zip 文件中包含 abc 目录,那么您的路径构建就是阻碍。尝试:

def unzip_artifact( local_directory, file_path ):
    fileName, ext = os.path.splitext( file_path )
    if ext == ".zip":
        print 'unzipping file ' + basename(fileName) + ext
        try:
            with zipfile.ZipFile(file_path) as zf:
                for member in zf.infolist():
                        # Path traversal defense copied from
                        # http://hg.python.org/cpython/file/tip/Lib/http/server.py#l789
                        zf.extract(member, local_directory)
        except zipfile.error, e:
            print "Bad zipfile: %s" % (e)
        return

或者更好的是只使用extractall:

def unzip_artifact( local_directory, file_path ):
    fileName, ext = os.path.splitext( file_path )
    if ext == ".zip":
        print 'unzipping file ' + basename(fileName) + ext
        try:
            zipfile.ZipFile(file_path).extractall(local_directory)
        except zipfile.error, e:
            print "Bad zipfile: %s" % (e)
        return
于 2013-09-02T17:43:04.563 回答