El código original está aquí

Para comprimir

  1. # Simple Application/Script to Compress a File or Directory
  2. # Essentially you could use this instead of Winzip
  3.  
  4. """
  5. Path can be a file or directory
  6. Archname is the name of the to be created archive
  7. """
  8. from zipfile import ZipFile, ZIP_DEFLATED
  9. import os  # File stuff
  10. import sys # Command line parsing
  11. def zippy(path, archive):
  12.     paths = os.listdir(path)
  13.     for p in paths:
  14.         p = os.path.join(path, p) # Make the path relative
  15.         if os.path.isdir(p): # Recursive case
  16.             zippy(p, archive)
  17.         else:
  18.             archive.write(p) # Write the file to the zipfile
  19.     return
  20.  
  21. def zipit(path, archname):
  22.     # Create a ZipFile Object primed to write
  23.     archive = ZipFile(archname, "w", ZIP_DEFLATED) # "a" to append, "r" to read
  24.     # Recurse or not, depending on what path is
  25.     if os.path.isdir(path):
  26.         zippy(path, archive)
  27.     else:
  28.         archive.write(path)
  29.     archive.close()
  30.     return "Compression of \""+path+"\" was successful!"
  31.  
  32. instructions = "zipit.py:  Simple zipfile creation script." + \
  33.                "recursively zips files in a directory into" + \
  34.                "a single archive." +\
  35.                "e.g.:  python zipit.py myfiles myfiles.zip"
  36.  
  37. # Notice the __name__=="__main__"
  38. # this is used to control what Python does when it is called from the
  39. # command line.  I'm sure you've seen this in some of my other examples.
  40. if __name__=="__main__":
  41.     if len(sys.argv) >= 3:
  42.         result = zipit(sys.argv[1], sys.argv[2])
  43.         print result
  44.     else:
  45.         print instructions
  46.  

Para descomprimir

  1. # Simple script to Unzip archives created by
  2. # our Zip Scripts.
  3.  
  4. import sys
  5. import os
  6. from zipfile import ZipFile, ZIP_DEFLATED
  7.  
  8. def unzip( path ):
  9.     # Create a ZipFile Object Instance
  10.     archive = ZipFile(path, "r", ZIP_DEFLATED)
  11.     names = archive.namelist()
  12.     for name in names:
  13.         if not os.path.exists(os.path.dirname(name)):
  14.             # Create that directory
  15.             os.mkdir(os.path.dirname(name))
  16.         # Write files to disk
  17.         temp = open(name, "wb") # create the file
  18.         data = archive.read(name) #read the binary data
  19.         temp.write(data)
  20.         temp.close()
  21.     archive.close()
  22.     return "\""+path+"\" was unzipped successfully."
  23.  
  24. instructions = "This script unzips plain jane zipfiles:"+\
  25.                "e.g.:  python unzipit.py myfiles.zip"
  26.  
  27. if __name__=="__main__":
  28.     if len(sys.argv) == 2:
  29.         msg = unzip(sys.argv[1])
  30.         print msg
  31.     else:
  32.         print instructions
  33.