python实现压缩文件

本文详细介绍了如何使用Python的内置库`zipfile`和`tarfile`来创建、读取和管理ZIP及TAR格式的压缩文件。通过实例代码,读者将学习到如何添加、删除和提取文件到压缩包中,以及如何处理压缩文件的加密和分块写入等高级特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import zipfile, os

class Zip:
    readme ="""
        input_path,out_path, filelist,zipfilename
        input_path,out_path,zipfilename type is str
    
    """
    def __init__(self,input_path,out_path, filelist,filename,pathflag = '/'):
        self.input_path = input_path
        self.out_path = out_path
        self.filelist = filelist
        self.filename = filename
        self._pathflag = pathflag

    def check(self):
        for date in [self.input_path, self.out_path, self.filename]:
            for ci in date:
                if type(ci) is str:
                    pass
                else:
                    return -1
        if  type(self.filelist) is list:
            pass
        else:
            return -1

    def get_zip_file(self,input_path:str, filelist:list,):
        """
        对目录进行深度优先遍历
        :param input_path:
        :param result:
        :return:
        """
        result = []
        tmp_filelist = filelist
        files = os.listdir(input_path)
        for file in files:
            if os.path.isdir(input_path + self._pathflag + file):
                pass
                #self.get_zip_file(input_path + '/' + file,filelist, result)
            else:
                if file in filelist and file not in result:
                    result.append(input_path +self._pathflag + file)
                    tmp_filelist.remove(file)
        if len(tmp_filelist) != 0:
            for i in tmp_filelist:
                print('not found file' +str(input_path) + str(i))
            return -1
        else:
            return result


    def zip_file_path(self):
        """
        压缩文件
        :param input_path: 压缩的文件夹路径
        :param output_path: 解压(输出)的路径
        :param output_name: 压缩包名称
        :return:
        """


        filelists_path =  self.get_zip_file(self.input_path, self.filelist,)

        if filelists_path != -1:
            f = zipfile.ZipFile(self.out_path + self._pathflag + self.filename, 'w', zipfile.ZIP_DEFLATED)
            for file in filelists_path:
                f.write(file)
            # 调用了close方法才会保证完成压缩
            f.close()
            return self.out_path + self.filename
        return '获取压缩文件失败!'

    def Zip(self):
        if self.check() == -1:
            return -1
        print(self.zip_file_path())


if __name__ == '__main__':
    Zip('C:\\Users\\11494\\Desktop\\emc\\','C:\\Users\\11494\\Desktop\\',['132.csv','125.csv','180 12.11.csv'],'ziptest.zip',pathflag='\\').Zip()
    print(Zip.readme)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值