当我们遇到大量小文件的传输时,一般会涉及到文件的压缩和解压,下面对zip的压缩解压直接上代码
压缩:
def zip_dir(dirname,zipfilename): """ | [email protected]: 压缩指定目录为zip文件 | [email protected]:dirname为指定的目录,zipfilename为压缩后的zip文件路径 | [email protected]:无 | [email protected]: """ 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): """ | [email protected]: 解压zip文件到指定目录 | [email protected]:zipfilename为zip文件路径,unziptodir为解压文件后的文件目录 | [email protected]:无 | [email protected]: """ 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('/'): p = os.path.join(unziptodir, name[:-1]) if os.path.exists(p): # 如果文件夹存在,就删除之:避免有新更新无法复制 shutil.rmtree(p) os.mkdir(p) 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()
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/8337.html