import zipfile
zipf = zipfile.ZipFile(zippath,'w') # 在路径中创建一个zip对象
# zippath:zip文件全路径,例:D:\Users\XXX\Desktop\arcgis\filename.zip
zipf.write(addedfilepath, arcname) # 写文件
# addedfilepath:将要压缩的文件
# arcname:文件在filename.zip中的相对位置
zipf.close() #关闭文件
os.remove(filepath) # 删除文件
# filepath:要删除的文件全路径
举例:将shp打包成zip
import zipfile
# @function:将指定文件打包成zip,并删除原文件
# @Author:PasserQi
# @Param:
# filepath:.shp文件全路径,例如D:\Users\PasserQi\Desktop\arcgis\data.shp
# @return:生成的zip文件
def shpFilesToZips(filepath):
shpname = os.path.basename(filepath)
shppath = os.path.dirname(filepath)
name = shpname.replace(".shp","")
zippath = os.path.join(shppath, name + ".zip")
# Get the files will be packaged
files =[]
# package
pre_len = len(os.path.dirname(shppath))
zipf = zipfile.ZipFile(zippath, 'w')
for parent, dirnames, filenames in os.walk(shppath):
for filename in filenames:
if '.zip' in filename:
continue
if name in filename:
pathfile = os.path.join(parent, filename)
arcname = pathfile.replace(shppath, '')
zipf.write(pathfile, arcname)
files.append(pathfile)
zipf.close()
print files
# delete files
for file in files:
if os.path.exists(file):
os.remove(file)
return zippath