簡體   English   中英

從zip歸檔文件中提取文件(不包括某些文件名)

[英]Extract files from zip archive excluding certain filenames

在Python中,如何在保留文件夾結構但從提取中排除某些文件名(文件類型)的同時提取zip歸檔文件? 例如,我要從提取中排除所有.tif圖像。

我正在使用Python 3.x和zipfile模塊。

將經過過濾的members傳遞給extractall() archive.extractall(members=(member for member in archive.namelist() if not member.endswith('.tif')))

def extractall(self, path=None, members=None, pwd=None):
    """Extract all members from the archive to the current working
       directory. `path' specifies a different directory to extract to.
       `members' is optional and must be a subset of the list returned
       by namelist().
    """
    if members is None:
        members = self.namelist()

    for zipinfo in members:
        self.extract(zipinfo, path, pwd)

自從我使用此例程已有一段時間以來,所以我不得不將其挖掘出來。 您可能要測試/適應您的特定需求。

排除if語句僅檢查要提取的文件名的最后三個字符,您可以使用.split('.')進行更改以檢查完整的擴展名,因為許多文件現在具有超過3個字符的擴展名。

這是為Windows編寫的,如果在其他操作系統上運行,則可能需要更改某些位

這段代碼保留了文件夾結構,但可能不是最快的例程(盡管我從未有過任何抱怨:

import zipfile


def unzip_file(zippedfile = '', targetdir = '', exclude_ext = ''):

    if zippedfile == '': ## this is the .zip file
        return
    if targetdir == '':
        targetdir = os.path.join(os.path.dirname(zippedfile), os.path.basename(zippedfile)[:-4])    
    if not os.path.exists (targetdir):
        os.makedirs (targetdir)

    zfile = zipfile.ZipFile(zippedfile)

    for name in zfile.namelist():
        (dirName, fileName) = os.path.split(name)
        if not dirName == '':
            if not os.path.exists (os.path.join(targetdir, dirName)):
                os.makedirs (os.path.join(targetdir, dirName))
        if fileName == '':
            # directory
            newDir = os.path.join(targetdir, dirName)
            if not os.path.exists(newDir):
                os.makedirs (newDir)
        else:
            # file
            if exclude_ext == '':
                print ('Extracting File : ' + name)
                fd = open(os.path.join(targetdir, name), 'wb')
                fd.write(zfile.read(name))
                fd.close()
            else:
                if not exclude_ext == name[-3:]:
                    print ('Extracting File : ' + name)
                    fd = open(os.path.join(targetdir, name), 'wb')
                    fd.write(zfile.read(name))
                    fd.close()                    
                else:
                    print ('File with extension ' + exclude_ext + ' is excluded')
    zfile.close()

    return

祝好運。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM