从zip存档中提取文件,不包括某些文件名



在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编写的,如果在其他OSS上运行,您可能需要更改某些位

此代码保留了文件夹结构,但可能不是最快的例行程序(尽管我从来没有任何投诉:

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

祝你好运。

最新更新