Python 解压文件、压缩文件(zip,rar)

1. python 解压zip压缩包或rar压缩包

import zipfile
# from unrar import rarfile   # python2
import rarfile  # python3


def zip_decompress(file_path, new_path):
    """支持中文的解压缩程序
       file_path:原压缩包文件路径
       new_path:新文件夹路径
    """
    if file_path.split('.')[-1] == 'zip':
        z = zipfile.ZipFile(file_path, 'r')
        z.extractall(path=new_path)
    else:
        z = rarfile.RarFile(file_path, 'r')
        z.extractall(path=new_path)


if __name__ == "__main__":
    file_path = r"C:\test\zip_test\Django.rar"
    new_path = r"C:\test\zip_test"
    zip_decompress(file_path, new_path)

2. python将文件/文件夹压缩为zip压缩包

import os
import zipfile


def zipDir(dirpath, target_path):
    """
    压缩指定文件夹
    :param dirpath: 目标文件夹路径
    :param target_path: 压缩文件保存路径
    """
    pre_len = len(os.path.dirname(target_path))
    zip = zipfile.ZipFile(target_path, "w", zipfile.ZIP_DEFLATED)
    for path, dirnames, filenames in os.walk(dirpath):
        # # 1.去掉目标跟路径,只对目标文件夹下边的文件及文件夹进行压缩
        # fpath = path.replace(dirpath, '')
        # for filename in filenames:
        #     pathfile = os.path.join(path, filename)
        #     arcname = os.path.join(fpath, filename)  # 归档文件
        #     zip.write(pathfile, arcname)

        # 2. 带文件夹压缩
        for filename in filenames:
            pathfile = os.path.join(path, filename)
            arcname = pathfile[pre_len:].strip(os.path.sep)  # 相对路径
            zip.write(pathfile, arcname)
    zip.close()


if __name__ == "__main__":
    dirpath = r"C:\test\zip_test\pdfconver"
    target_path = r"C:\test\zip_test\pdfconver.zip"
    zipDir(dirpath, target_path)

  • 8
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值