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

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

    文件解压缩

    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)  # 有密码时需要传入第三个参数pwd
                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)
  • 相关阅读:
    【转贴】Cookie + Session + OAuth + SSO
    zz淘宝商品库MySQL优化实践
    HIVE 数据倾斜调优总结zz
    数据挖掘笔记(一)
    hive函数参考手册
    hive QL(HQL)简明指南zz
    数据挖掘笔记(二)
    python format string (转)
    hive 中转义符使用问题
    关于文档管理
  • 原文地址:https://www.cnblogs.com/lnd-blog/p/14873666.html
Copyright © 2011-2022 走看看