zip a folder and its content


/ Published in: Python
Save to your folder(s)



Copy this code and paste it in your HTML
  1. import zipfile
  2. import os,stat
  3. from cStringIO import StringIO
  4.  
  5. def createZip(path):
  6.  
  7. def walktree (top = ".", depthfirst = True):
  8. names = os.listdir(top)
  9. if not depthfirst:
  10. yield top, names
  11. for name in names:
  12. try:
  13. st = os.lstat(os.path.join(top, name))
  14. except os.error:
  15. continue
  16. if stat.S_ISDIR(st.st_mode):
  17. for (newtop, children) in walktree (os.path.join(top, name),
  18. depthfirst):
  19. yield newtop, children
  20. if depthfirst:
  21. yield top, names
  22.  
  23. list=[]
  24. for (basepath, children) in walktree(path,False):
  25. for child in children:
  26. f=os.path.join(basepath,child)
  27. if os.path.isfile(f):
  28. f = f.encode(sys.getfilesystemencoding())
  29. list.append( f )
  30.  
  31. f=StringIO()
  32. file = zipfile.ZipFile(f, "w")
  33. for fname in list:
  34. nfname=os.path.join(os.path.basename(path),fname[len(path)+1:])
  35. file.write(fname, nfname , zipfile.ZIP_DEFLATED)
  36. file.close()
  37.  
  38. f.seek(0)
  39. return f

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.