zip文件操作

作者: LCSan | 来源:发表于2020-05-05 12:58 被阅读0次
    #coding=utf-8
    '''
    zip,rar 压缩/解压缩 插件
    
    Created on 2019年3月10日
    
    @author: 瞌睡蟲子
    '''
    import zipfile, os
    
    def unZip(zipPath, dirPath=None, pwd=None, coding="UTF8"):
        """
        `压缩文件列表
        :param zipPath: 压缩文件路径+xxxx.zip    
        :param dirpath: 解压路径
        :param pwd: 解压密码 
        :param coding: 编码格式 GBK,UTF8,MAC_UTF8
        :return: 文件列表
        """
        if pwd == "":
            pwd = None
        if zipfile.is_zipfile(zipPath):
            tempzip = zipfile.ZipFile(zipPath)
            temp = []
            sf = ""
            for zip_file in tempzip.namelist():
                tempzip.extract(zip_file, dirPath, pwd)
                os.chdir(dirPath)
                if coding.lower() == "gbk":
                    sf = zip_file.encode('cp437').decode('gbk')
                    os.rename(zip_file, sf)
                elif coding.lower() == "utf8":
                    sf = zip_file.encode('utf-8').decode('utf-8')
                    os.rename(zip_file, sf)
                elif coding.lower() == "mac_utf8":
                    sf = zip_file.encode('cp437').decode('utf-8')
                    os.rename(zip_file, sf)
                else:
                    raise Exception("不支持该编码格式")
                if zip_file != sf:
                    temp.append(zip_file)
            tempzip.close()
            # 根据字符串长度倒叙,从文件开始删除
            temp.sort(key = lambda i:len(i),reverse=True) 
            for fe in temp:
                if os.path.exists(fe): 
                    if os.path.isfile(fe):
                        os.remove(fe)
                    if os.path.isdir(fe):
                        os.rmdir(fe)
                    # for root, dirs, files in os.walk(fe, topdown=False):
                    #     for name in files:
                    #         try:
                    #             os.remove(os.path.join(fe, name))
                    #         finally:
                    #             pass
                    #     for name in dirs:
                    #         try:
                    #             os.rmdir(os.path.join(fe, name))
                    #         finally:
                    #             pass                            
                    # os.rmdir(fe)
            
        
    def showZip(zipPath, coding="UTF8"):
        """
        `压缩文件列表
        :param zipPath: 压缩文件路径+xxxx.zip    
        :param coding: 编码格式 GBK,UTF8,MAC_UTF8
        :return: 文件列表
        """
        res = []
        tempzip = zipfile.ZipFile(zipPath)
        for zip_file in tempzip.namelist():
            if coding.lower() == "gbk":
                res.append(zip_file.encode('cp437').decode('gbk'))
            elif coding.lower() == "utf8":
                res.append(zip_file.encode('utf-8').decode('utf-8'))
            elif coding.lower() == "mac_utf8":
                res.append(zip_file.encode('cp437').decode('utf-8'))
            else:
                raise Exception("不支持该编码格式")
        tempzip.close()
        return res
    
    def zipFiles(zipPath, files):
        """
        `压缩指定文件列表
        :param zipPath: 压缩文件路径+xxxx.zip
        :param files: 目标文件列表。内容可以是文件或文件夹
        :return: 无        
        """
        tempzip = zipfile.ZipFile(zipPath,"w",zipfile.ZIP_DEFLATED)
        for fe in files:
            if os.path.isfile(fe):
                tempzip.write(fe,os.path.basename(fe))
            elif os.path.isdir(fe):
                for path,dirnames,filenames in os.walk(fe):
                    # 去掉目标跟路径,只对目标文件夹下边的文件及文件夹进行压缩
                    fpath = path.replace(os.path.dirname(fe),'')        
                    for filename in filenames:
                        tempzip.write(os.path.join(path,filename),os.path.join(fpath,filename))            
        tempzip.close()
    
    if __name__ == "__main__":
        ""
    #     unZip("C:\\Users\\Administrator\\Desktop\\xxx.zip", "D:\\aa", None, "mac_utf8")
        # unZip("C:\\Users\\Administrator\\Desktop\\xxx.zip", r"C:\Users\Administrator\Desktop\aaa", None,"gbk")
    #     aa=showZip("D:/bbb.zip","utf8")
    #     print(aa)
    #     zipDir("D:/aaaa.zip","D:/aa")
        # zipFiles("D:/bbb.zip",[r"E:\BaiduNetdiskDownload\UiBotCreator\extend\python"])
        #递归遍历“rootdir”目录下的指定后缀的文件列表
    #     getFiles("D:\验证码")
        # print(os.path.dirname(r"E:\BaiduNetdiskDownload\UiBotCreator\extend"))
            
    

    相关文章

      网友评论

        本文标题:zip文件操作

        本文链接:https://www.haomeiwen.com/subject/gikmghtx.html