用python解压缩

问题描述 投票:0回答:2

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

我的文件为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
python python-2.7 extract unzip
2个回答
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

0
投票
def extracter(file_name, extraction_path):
    """
    Common method to extract tar files parameter includes source directory and destination directory
    :param file_name:
    :param extraction_path:
    """
    if not file_name.exists():
        print("Oops, file doesn't exist!")
    else:
        if tarfile.is_tarfile(file_name):
            tf = tarfile.open(file_name, 'r:*')
            tf.extractall(extraction_path)
            tf.close()

使用源方法和目标方法调用该方法。它处理所有类型的tar文件。不需要额外的文件处理。

© www.soinside.com 2019 - 2024. All rights reserved.