编程语言
首页 > 编程语言> > 批量压缩文件夹-Python程序-效果演示

批量压缩文件夹-Python程序-效果演示

作者:互联网

代码效果演示
Gitee源码

# -*- coding: utf-8 -*-
# Version: Python 3.9.7
# Author: TRIX
# Date: 2021-10-02 13:20:04
# Use: 批量压缩指定文件夹 为zip压缩包
import zipfile
from os import path,walk,chdir
def zipFiles(pathsList):#需要压缩的文件夹 或 文件列表
	for i,r in enumerate(pathsList,1):
		if path.isfile(r):#如果是文件
			fDir,fName=path.split(r)
			fPre,fSuf=path.splitext(fName)
			chdir(fDir)#改变当前工作目录

			zipPath=fDir+'\\'+fPre+'.zip'#压缩包路径
			zipObj = zipfile.ZipFile(zipPath, 'w', zipfile.ZIP_DEFLATED)#以 deflate压缩算法 w模式 创建zip对象
			zipObj.write(fName)
			zipObj.close()
		else:#如果是文件夹
			chdir(r)#改变当前工作目录
			fDir,fName=path.split(r)
			fPre,fSuf=path.splitext(fName)
			zipPath=fDir+'\\'+fName+'.zip'
			zipObj = zipfile.ZipFile(zipPath, 'w', zipfile.ZIP_DEFLATED)#以 deflate压缩算法 w模式 创建zip对象
			for p, dirs, files in walk(r):
				for name in files:#拼接文件名
					zPath=path.join(p, name).replace(r+'\\','')
					zipObj.write(zPath)
				for name in dirs:#拼接目录名
					zPath=path.join(p, name).replace(r+'\\','')
					zipObj.write(zPath)
			zipObj.close()

		print('第{}个文件夹压缩完毕,储存路径{}'.format(i,zipPath))

pathsList=[
r'D:\[download]\forTest\folder_for_test\FFT1',
r'D:\[download]\forTest\folder_for_test',r'D:\[download]\forTest\folder_for_test\新建 Microsoft Excel 工作表.xlsx']
zipFiles(pathsList)

标签:演示,zip,Python,zipObj,zipfile,文件夹,fName,fDir,path
来源: https://www.cnblogs.com/Trix/p/15362420.html