簡體   English   中英

python解壓根目錄下的文件

[英]python unzip files below the root folder

我想解壓縮根文件夾下的所有存檔文件夾和文件,我有一個名為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

您必須使用更復雜(因此更可自定義)的方式解壓縮。 不能使用“ extractall”方法,而必須使用“ extract”方法分別提取每個文件。 然后,您將能夠更改目標目錄,而無需歸檔的子目錄。

這是您需要修改的代碼:

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