本文實(shí)例講述了Python實(shí)現(xiàn)壓縮文件夾與解壓縮zip文件的方法。分享給大家供大家參考,具體如下:
創(chuàng)新互聯(lián)公司專(zhuān)業(yè)為企業(yè)提供慶云網(wǎng)站建設(shè)、慶云做網(wǎng)站、慶云網(wǎng)站設(shè)計(jì)、慶云網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁(yè)設(shè)計(jì)與制作、慶云企業(yè)網(wǎng)站模板建站服務(wù),十年慶云做網(wǎng)站經(jīng)驗(yàn),不只是建網(wǎng)站,更提供有價(jià)值的思路和整體網(wǎng)絡(luò)服務(wù)。直接上代碼
#coding=utf-8 #甄碼農(nóng)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')