0

我想解压缩根文件夹下存档的所有文件夹和文件,我有一个名为 abc.zip 的存档,它给我的文件为 abc/xyz/abc/123.jpg abc/xyz1/,我只想提取 xyz / , 123.jpg 和 xyz1/ 在 CWD

我使用下面的代码来提取文件,但需要有关如何省略列表的根文件夹的帮助

def unzip_artifact(local_directory, file_path):

fileName, ext = os.path.splitext( file_path )

if ext == ".zip":

Downloadfile = basename(fileName) + ext

    print 'unzipping file ' + Downloadfile

    try:
    zipfile.ZipFile(file_path).extractall(local_directory)

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

1 回答 1

0

您必须使用更复杂(因此更可定制)的方式来解压缩。您必须使用 'extract' 方法分别提取每个文件,而不是使用 'extractall' 方法。然后您将能够更改目标目录,省略存档的子目录。

这是您需要修改的代码:

def unzip_artifact( local_directory, file_path ):

    fileName, ext = os.path.splitext( file_path )
    if ext == ".zip":
        Downloadfile = fileName + ext
        print 'unzipping file ' + Downloadfile

        try:
            #zipfile.ZipFile(file_path).extractall(local_directory) # Old way
            # Open the zip
            with zipfile.ZipFile(file_path) as zf:
                # For each members of the archive
                for member in zf.infolist():
                    # If it's a directory, continue
                    if member.filename[-1] == '/': continue
                    # Else write its content to the root
                    with open(local_directory+'/'+os.path.basename(member.filename), "w") as outfile:
                        outfile.write(zf.read(member))

        except zipfile.error, e:
            print "Bad zipfile: %s" % (e)
        return
于 2014-06-25T12:10:53.303 回答