[全网唯一]通过修改源码使得从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则默认原命名)

posted @ 2023-10-25 21:23  挥手捧星落  阅读(63)  评论(0编辑  收藏  举报