美文网首页Python
利用Python实现压缩一个文件夹

利用Python实现压缩一个文件夹

作者: 傻逼平台瞎几把封号 | 来源:发表于2022-07-25 15:18 被阅读0次

利用Python实现压缩一个文件夹

二、知识点

  • 文件读写
  • 基础语法
  • 字符串处理
  • 循环遍历
  • 文件压缩

三、代码解析

导入系统包

import platform
import os
import zipfile

主要代码

def do_zip_compress(dirpath):
    print("原始文件夹路径:" + dirpath)
    output_name = f"{dirpath}.zip"
    parent_name = os.path.dirname(dirpath)
    print("压缩文件夹目录:", parent_name)
    zip = zipfile.ZipFile(output_name, "w", zipfile.ZIP_DEFLATED)
    # 多层级压缩
    for root, dirs, files in os.walk(dirpath):
        for file in files:
            if str(file).startswith("~$"):
                continue
            filepath = os.path.join(root, file)
            print("压缩文件路径:" + filepath)
            writepath = os.path.relpath(filepath, parent_name)
            zip.write(filepath, writepath)
    zip.close()

需要先创建文件夹resources

dirpath = r"./resources"

压缩文件夹

do_zip_compress(dirpath)

四、运行结果

Python爬虫入门到实战全集100集教程:代码总是学完就忘记?100个爬虫实战项目!让你沉迷学习丨学以致用丨下一个Python大神就是你!

Python tkinter 合集:全网最全python tkinter教程!包含所有知识点!轻松做出好看的tk程序!

相关文章

网友评论

    本文标题:利用Python实现压缩一个文件夹

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