zoukankan      html  css  js  c++  java
  • python中如何压缩和解压缩文件

    在实际的业务开发中会经常遇到对文件进行相关的操作,比如新建文件夹或文件,移动、删除文件夹或文件,文件的压缩与解压缩等等!!下面就其中的压缩与解压缩进行代码演示!

    import os
    import glob
    import zipfile

    文件解压缩

    def unzip_file(dir_path):
        # 解压缩后文件的存放路径
        unzip_file_path = r"C:UsersDesktop新建文件夹"
        # 找到压缩文件夹
        dir_list = glob.glob(dir_path)
        if dir_list:
            # 循环zip文件夹
            for dir_zip in dir_list:
                # 以读的方式打开
                with zipfile.ZipFile(dir_zip, 'r') as f:
                    for file in f.namelist():
                        f.extract(file, path=unzip_file_path)
                os.remove(dir_zip)
    
    
    unzip_file(r"C:UsersDesktop新建文件夹*.zip")
    
    # 这儿的 dir_path 只是其中的一种路径处理方式,可以根据自己的需求行进实际操作
    

    文件压缩

    压缩目标目录下的所有文件

    def zip_files(dir_path, zip_path):
        """
        :param dir_path: 需要压缩的文件目录
        :param zip_path: 压缩后的目录
        :return:
        """
        with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as f:
            for root, _, file_names in os.walk(dir_path):
                for filename in file_names:
                    f.write(os.path.join(root, filename), filename)

      

  • 相关阅读:
    :where()和:is()
    响应式布局(媒体查询+rem)
    v-html的问题及解决办法
    Sticky Footer(粘性页脚)
    css多行文字垂直居中
    BFC
    margin负值的情况
    windows系统设置环境变量
    hash和history原生事件
    腾讯WeTest零售行业质量解决方案
  • 原文地址:https://www.cnblogs.com/rongge95500/p/11271764.html
Copyright © 2011-2022 走看看