• [全网唯一]通过修改源码使得从ZIP提取文件并在提取时进行重命名保存(博客园同步发布)


    源码位置: /Lib/zipfile.py/ZipFile/_extract_member/zipfile.py或者直接点击extract函数.

    在使用python解压缩zip文件时, 由于需要在解压时重命名文件为我想要的格式, 而不巧的是, zipfile包官方源代码没有这个功能...

    于是, 在百度之后, 果断放弃寻找现成代码的想法.

    在研究了一下extract函数的原源代码后, 觉得可以加一个参数targetname用来指代重命名后的文件名, 而很巧的是, 这个新参数并没有在源代码中使用, 所以加入它没有影响.

    Talk is easy, show you code~

    代码展示

    row 1618
        def extract(self, member, path=None, pwd=None,targetname=None):
            """targetname : the name extracted rename to targetname
             
                Extract a member from the archive to the current working directory,
               using its full name. Its file information is extracted as accurately
               as possible. `member' may be a filename or a ZipInfo object. You can
               specify a different directory using `path'.
            """
            if path is None:
                path = os.getcwd()
            else:
                path = os.fspath(path)
      
            return self._extract_member(member, path, pwd,targetname)
      
        def extractall(self, path=None, members=None, pwd=None,targetname=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()
      
            if path is None:
                path = os.getcwd()
            else:
                path = os.fspath(path)
      
            for zipinfo in members:
                self._extract_member(zipinfo, path, pwd,targetname)
    row 1650
    ...
    row 1665
    def _extract_member(self, member, targetpath, pwd,targetname):
            """Extract the ZipInfo object 'member' to a physical
               file on the path targetpath.
            """
            if not isinstance(member, ZipInfo):
                member = self.getinfo(member)
      
            # build the destination pathname, replacing
            # forward slashes to platform specific separators.
            arcname = member.filename.replace('/', os.path.sep)
      
            if os.path.altsep:
                arcname = arcname.replace(os.path.altsep, os.path.sep)
            # interpret absolute pathname as relative, remove drive letter or
            # UNC path, redundant separators, "." and ".." components.
            arcname = os.path.splitdrive(arcname)[1]
            invalid_path_parts = ('', os.path.curdir, os.path.pardir)
            arcname = os.path.sep.join(x for x in arcname.split(os.path.sep)
                                       if x not in invalid_path_parts)
            if os.path.sep == '\\':
                # filter illegal characters on Windows
                arcname = self._sanitize_windows_name(arcname, os.path.sep)
            if targetname is None:
                targetpath = os.path.join(targetpath, arcname)
                targetpath = os.path.normpath(targetpath)
            else:
                targetpath = os.path.normpath(targetpath)
      
            # Create all upper directories if necessary.
            upperdirs = os.path.dirname(targetpath)
            if upperdirs and not os.path.exists(upperdirs):
                os.makedirs(upperdirs)
      
            if member.is_dir():
                if not os.path.isdir(targetpath):
                    os.mkdir(targetpath)
                return targetpath
            if targetname is None:
                with self.open(member, pwd=pwd) as source, \
                    open(targetpath, "wb") as target:
                    shutil.copyfileobj(source, target)
            else:
                with self.open(member, pwd=pwd) as source, \
                    open(targetpath+"/"+targetname, "wb") as target:
                    shutil.copyfileobj(source, target)
      
            return targetpath
    row 1713

      用法

    可以直接粘贴到自己的源码中, 如果担心出现其他bug, 可以用完就重装zipfile.

    调用extract时传入三个参数: 压缩包名称, 目标目录, 目标名称(重命名后的名字, 如果为None则默认原命名)

  • 相关阅读:
    仓库管理系统怎么选?想高效管理仓库的老板,别错过这篇干货!
    Web服务器配置与管理
    JavaScript红宝书第七章:迭代器与生成器
    物联网智能油井控制系统
    协同云办公原来可以这么简单!只需掌握这5个技巧
    [ Linux ] 进程间通信之共享内存
    [leetcode hot 150]第十五题,三数之和
    每个程序员都应该了解的 10 大隐私计算技术
    MinIO图片正常上传不可查看,MinIO通过页面无法设置桶为public
    Java网络
  • 原文地址:https://www.cnblogs.com/zenolab/p/17788173.html