在Python中,如何在保存文件夹结构的同时提取zip存档,但从提取中排除某些文件名(文件类型)?例如,我希望从提取中排除所有.tif图像。
我使用Python3.x和zipfile模块。
发布于 2016-06-21 15:19:52
将过滤后的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)发布于 2016-06-21 16:30:19
我已经有一段时间没有使用这个例行公事了,所以我不得不把它挖出来。你可能想测试/适应你的特定需求。
排除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祝好运。
https://stackoverflow.com/questions/37948283
复制相似问题