python解压缩根文件夹下的文件

时间:2013-09-13 06:51:50

标签: python root unzip directory

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

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

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

1 个答案:

答案 0 :(得分: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