首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从zip归档中提取文件,不包括某些文件名

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

Stack Overflow用户
提问于 2016-06-21 15:14:05
回答 2查看 1.6K关注 0票数 0

在Python中,如何在保存文件夹结构的同时提取zip存档,但从提取中排除某些文件名(文件类型)?例如,我希望从提取中排除所有.tif图像。

我使用Python3.x和zipfile模块。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-06-21 15:19:52

将过滤后的members传递给extractall()archive.extractall(members=(member for member in archive.namelist() if not member.endswith('.tif')))

代码语言:javascript
运行
复制
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)
票数 2
EN

Stack Overflow用户

发布于 2016-06-21 16:30:19

我已经有一段时间没有使用这个例行公事了,所以我不得不把它挖出来。你可能想测试/适应你的特定需求。

排除if语句只检查要提取的文件名的最后三个字符,您可以使用.split('.')更改它以检查完整的扩展名,因为现在许多文件的扩展名超过3个字符。

这是为Windows编写的,如果在其他操作系统上运行,您可能需要更改某些位

这段代码保存了文件夹结构,但可能不是最快的例程(尽管我从来没有收到过任何抱怨:

代码语言:javascript
运行
复制
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

祝好运。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37948283

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档