标签:
1 __author__ = ‘Zechary‘ 2 3 import os, os.path 4 import zipfile 5 6 def zip_dir(dirname, zipname): 7 filelist = [] 8 if os.path.isfile(dirname): 9 filelist.append(dirname) 10 else: 11 for root, dirs, files in os.walk(dirname): 12 for name in files: 13 filelist.append(os.path.join(root, name)) 14 15 zf = zipfile.ZipFile(zipname, "w", zipfile.zlib.DEFLATED) 16 for tar in filelist: 17 zf.write(tar) 18 zf.close() 19 20 def unzip_file(zipfilename, unziptodir): 21 if not os.path.exists(unziptodir): 22 os.mkdir(unziptodir, 0777) 23 zfobj = zipfile.ZipFile(zipfilename) 24 for name in zfobj.namelist(): 25 name = name.replace(‘\\‘, ‘/‘) 26 if name.endswith(‘/‘): 27 os.mkdir(os.path.join(unziptodir, name)) 28 else: 29 ext_filename = os.path.join(unziptodir, name) 30 ext_dir = os.path.dirname(ext_filename) 31 if not os.path.exists(ext_dir): 32 os.mkdir(ext_dir, 0777) 33 outfile = open(ext_filename, ‘wb‘) 34 outfile.write(zfobj.read(name)) 35 outfile.close() 36 37 if __name__ == "__main__": 38 zip_dir(‘D:\pythontest‘, ‘D:\pythontest.zip‘) 39 unzip_file(‘D:\\pythontest.zip‘, ‘D:\\pythontest111‘)
标签:
原文地址:http://www.cnblogs.com/xiaojiangdraug/p/4507453.html