简体   繁体   English

python解压根目录下的文件

[英]python unzip files below the root folder

i would like to unzip all the folders and files of an archive below the root folder, i have archive named abc.zip which gives me files as abc/xyz/ abc/123.jpg abc/xyz1/ , i just want to extract xyz/ , 123.jpg and xyz1/ in the CWD 我想解压缩根文件夹下的所有存档文件夹和文件,我有一个名为abc.zip的存档,它给我的文件为abc / xyz / abc / 123.jpg abc / xyz1 /,我只想提取xyz /,123.jpg和xyz1 /在CWD中

i use below code to extract a file, but would need help on how to omit the root folder of the list 我使用下面的代码提取文件,但需要有关如何省略列表根文件夹的帮助

def unzip_artifact( local_directory, file_path ): 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

You have to use a more complex (and therefore more customizable) way to unzip. 您必须使用更复杂(因此更可自定义)的方式解压缩。 Instead of using the 'extractall' method, you must extract each files separately with the 'extract' method. 不能使用“ extractall”方法,而必须使用“ extract”方法分别提取每个文件。 Then you will be able to change the destination directory, omitting archive's sub-directories. 然后,您将能够更改目标目录,而无需归档的子目录。

Here is your code with the modification you needed : 这是您需要修改的代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM