? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Python —— 压缩文件夹
目标:压缩指定文件夹为zip文件
适用场景:批处理文件,定时打包并发送至指定用户邮箱
python脚本如下:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@Author :xxxxx
@Contact :1223242863@qq.com
@File :zip.py
@Time :2021/8/17 11:27 PM
@Software :Pycharm
@Copyright (c) 2021,All Rights Reserved.
"""
import os
import zipfile
from loguru import logger
def getZipDir(dirpath, outFullName):
"""
压缩指定文件夹
:param dirpath: 目标文件夹路径
:param outFullName: 压缩文件保存路径+xxxx.zip
:return: 无
"""
zip = zipfile.ZipFile(outFullName, "w", zipfile.ZIP_DEFLATED)
for path, dirnames, filenames in os.walk(dirpath):
# 去掉目标跟路径,只对目标文件夹下边的文件及文件夹进行压缩
fpath = path.replace(dirpath, '')
for filename in filenames:
zip.write(os.path.join(path, filename), os.path.join(fpath, filename))
zip.close()
logger.info("文件夹\"{0}\"已压缩为\"{1}\".".format(dirpath, outFullName))
if __name__ == "__main__":
getZipDir(dirpath="/Users/xxxxx/Desktop/台大林轩田机器学习基石课程学习笔记",
outFullName="/Users/xxxxx/Desktop/test.zip")
|