1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | #coding=utf8 import os import zipfile import sys,locale # 本来以为需要,结果不需要 # def p(f): # #print '%s.%s(): %s' % (f.__module__, f.__name__, f()) # return f() # # # sys_decode= p(locale.getdefaultlocale)[1] # print sys_decode def unzip_file(zipfilename, unziptodir): if not os.path.exists(unziptodir): os.makedirs(unziptodir, 0777 ) zfobj = zipfile.ZipFile(zipfilename) for name in zfobj.namelist(): if name.endswith( '/' ) : path = os.path.join(unziptodir, name) if not os.path.exists(path): os.makedirs(path) 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__' : unzip_file( 'C:\\Users\\Administrator\\Desktop\\201712271043_life_v18.1.zip' , 'D:\\test' ) |
参考网站https://www.oschina.net/code/snippet_89296_9122
参考代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | #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' ) |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步