Zipping files in python

Every so often I run an automated process that copies all of our clients data to file geodatabases and then zips them up to post to the web. Previously I used PKZip as a command line zipper, calling it from my python script in a batch file. I decided to explore the possibility of zipping from within python. Turns out there is a module called zipfile that does just what I need. A fellow blogger got me started on the right path with a very helpful blog posting (here it is).

# Description: 
# run this after creating the gis data for the web script
import sys, string, os, zipfile
#if available add compression
    import zlib
    compressType = zipfile.ZIP_DEFLATED
    compressType = zipfile.ZIP_STORED
shpPath = "N:/yourpath/datafiles"
# Read the list of shapefiles and zip'em
# shapefiles have a prefix that determines what zip file the go in
# reads the files alphabetically, or this script wouldn't work
# if the zip file already exists, it will overwrite
x = 0
currentZip = ''
  itemList = os.listdir(shpPath)
  for i in itemList:
    fullpath = os.path.join(shpPath, i)
    shpName = i.split("_",1)  # the data naming convention for the data includes an underscore.  This reads the prefix and name into a list
    thisZip = shpName[0] # reads the prefix
    shp = shpName[1] #reads the name of the file
    zipname = 'ClientName_' + thisZip +''  #add a new prefix (ClientName_) and groups all the like prefixes into one zip.  So... all the transportation data is in one zip file.
    if i <> zipname:
      if currentZip == thisZip:
        #add to zip archive
        zf = zipfile.ZipFile(shpPath + '/zips/'+ zipname, mode='a')
            print 'adding', i
            zf.write(fullpath, arcname='ClientName_'+ i, compress_type=compressType)   #this writes the zip file
            #arcname sets the name and strips the folder location from the saved path internal to the zip file
        #make a new archive and set the new currentZip variable
        currentZip = thisZip
        print '\ncreating new archive'
        zf = zipfile.ZipFile(shpPath + '/zips/'+ zipname, mode='w')
          print 'adding', i
          zf.write(fullpath, arcname='ClientName_'+i, compress_type=compressType)
          print "Unexpected error:", sys.exc_info()[1]
      print 'cannot zip a zip file'
  print "Unexpected error:", sys.exc_info()[1]

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s