zipFile模块--python压缩文件

上一篇 / 下一篇  2017-09-06 10:07:54 / 个人分类:python

步骤和常用命令:
1)使用命令 'import zipfile'导入模块
2)创建ZipFile对象------A=zipfile.ZipFile('filename.zip')
3)返回ZipFile对象A中的所有文件和文件夹名------A.namelist()
4)返回ZipFile对象A中的ZipInfo对象,ZipInfo对象有自己的属性------B=A.getInfo('filename')
5)ZipInfo对象B的属性:原文件的大小------B.file_size
6)ZipInfo对象B的属性:压缩后文件的大小------B.compress_size
7)解压文件压缩文件A------A.extractall()
8)写模式创建ZipFile对象------C=zipfile.ZipFile('filename.zip','w')
9)写模式ZipFile对象下添加信息到ZIP文件中------C.write('path\\filename',compress_type=zipfile.ZIP_DEFLATED) zipfile.ZIP_DEFLATED用于指定压缩算法,对各种类型的数据都有效

练习代码1
#-*- coding:utf-8 -*-
import os,zipfile
# #TODO: 读取zip文件
# os.chdir('d:\\')
# exampleZip=zipfile.ZipFile('delicious.zip')
# print exampleZip.namelist()
# sampInfo=exampleZip.getinfo('delicious/spam.txt')
# print sampInfo.file_size #原来文件大小
# print sampInfo.compress_size #压缩文件大小
# print ('delicious file is %sx smaller ' %(round(sampInfo.file_size/sampInfo.compress_size,2))) #计算压缩效率
# exampleZip.close()
#
# #TODO: 解压zip文件
# os.chdir('d:\\')
# exampleZip=zipfile.ZipFile('delicious.zip') #如果已经存在解压目录也不会报错
# exampleZip=zipfile.ZipFile('delicious.zip')
# exampleZip.extractall('c:\\') #解压整个压缩包到指定路径
# exampleZip.extract('delicious/spam.txt','c:\\delicious') #解压文件到指定目录
# exampleZip.close()

# #TODO: 创建和添加到zip文件
# os.chdir('c:\\')
# newZip=zipfile.ZipFile('delicious.zip','w')
# newZip.write('delicious/spam.txt',compress_type=zipfile.ZIP_DEFLATED) #'delicious/spam.txt'地址必须为除根目录以外的全部地址,此处spam.txt文件必须存在于原zip文件
# newZip.close()


练习代码2
#-*- coding:utf-8 -*-
import os,zipfile
def backupToZip(folder):
floder=os.path.abspath(folder) #make sure folder is absolute
#figure out the filename this code should use based on what files already exist
number=1
while True:
zipFileName=str(os.path.basename(folder))+'_'+str(number)+'.zip' #os.path.basename 获取最后一个斜杠后的名称(文件加或文件名)
print os.path.basename(folder)
if not os.path.exists(zipFileName):
break
number=number+1
print 'Creating %s……' %zipFileName
# os.chdir('D:\\') #设置压缩包保存的路径,如果不设置默认保存在当前py文件执行路径下
backupZip=zipfile.ZipFile(zipFileName,'w') #写模式创建zip文件


#TODO:遍历目录树,且压缩目录下每一个文件夹 Walk the folder tree and compress the files in each folder
for flodername,subFolders,fileNmaes in os.walk(floder):
print ('Adding files in %s' %(flodername))
backupZip.write(flodername)
for filename in fileNmaes:
newBase= str(os.path.basename(floder))+'_'
if filename.startswith(newBase) and filename.endswith('.zip'):
continue
backupZip.write(os.path.join(flodername,filename))
# print backupZip.write(os.path.join(flodername,filename))
backupZip.close()
print 'done……'
backupToZip('D:\\delicious')


TAG:

 

评分:0

我来说两句

Open Toolbar