Python 压缩/解压文件夹
248 views
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # #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'/home/homer/test', r'/home/homer/test.zip') unzip_file(r'/home/homer/test2.zip',r'/home/homer/test2')
版权所有: 本文系米扑博客原创、转载、摘录,或修订后发表,最后更新于 2014-04-21 23:13:30
侵权处理: 本个人博客,不盈利,若侵犯了您的作品权,请联系博主删除,莫恶意,索钱财,感谢!
转载注明: Python 压缩/解压文件夹 (米扑博客)