本文实例讲述了Python实现压缩文件夹与解压缩zip文件的方法。分享给大家供大家参考,具体如下:
创新互联公司专业为企业提供庆云网站建设、庆云做网站、庆云网站设计、庆云网站制作等企业网站建设、网页设计与制作、庆云企业网站模板建站服务,十年庆云做网站经验,不只是建网站,更提供有价值的思路和整体网络服务。直接上代码
#coding=utf-8 #甄码农python代码 #使用zipfile做目录压缩,解压缩功能 import os,os.path import zipfile def zip_dir(dirname,zipfilename): filelist = [] if os.path.isfile(dirname): filelist.append(dirname) else : for root, dirs, files in os.walk(dirname): for name in files: filelist.append(os.path.join(root, name)) zf = zipfile.ZipFile(zipfilename, "w", zipfile.zlib.DEFLATED) for tar in filelist: arcname = tar[len(dirname):] #print arcname zf.write(tar,arcname) zf.close() def unzip_file(zipfilename, unziptodir): if not os.path.exists(unziptodir): os.mkdir(unziptodir, 0777) zfobj = zipfile.ZipFile(zipfilename) for name in zfobj.namelist(): name = name.replace('\\','/') if name.endswith('/'): os.mkdir(os.path.join(unziptodir, name)) else: ext_filename = os.path.join(unziptodir, name) ext_dir= os.path.dirname(ext_filename) if not os.path.exists(ext_dir) : os.mkdir(ext_dir,0777) outfile = open(ext_filename, 'wb') outfile.write(zfobj.read(name)) outfile.close() if __name__ == '__main__': zip_dir(r'E:/python/learning',r'E:/python/learning/zip.zip') unzip_file(r'E:/python/learning/zip.zip',r'E:/python/learning2')