Zipping a shapefile using python

UPDATE:

After receiving a request to modify the code to ignore .lock files, I have an updated to this post.

One of the tasks I’ve been automating is publishing a weekly data update to a website. The update consists of shapefile. The trouble with shapefiles is they consist of 3 or more files with the same basename but different extensions in the same directory.

Not an overly complicated situation but a common one that ArcGIS does not have a solution out-of-the-box. Below is a bare-bones code snippet to do it. It has both the input shapefile and output zip file hard-coded. The call to the subroutine that does the work is: zipShapefile(wellsShapeFile,wellsZipFile)

import zipfile
import sys
import os
import glob
wellsShapeFile = "C:/cwi5_bk/WELLS/wells.SHP"
wellsZipFile = "C:/cwi5_bk/WELLS/test5.zip"

def zipShapefile(inShapefile, newZipFN):
   print 'Starting to Zip '+inShapefile+' to '+newZipFN

if not (os.path.exists(inShapefile)):
   print inShapefile + ' Does Not Exist'
   return False

if (os.path.exists(newZipFN)):
   print 'Deleting '+newZipFN
   os.remove(newZipFN)

if (os.path.exists(newZipFN)):
   print 'Unable to Delete'+newZipFN
   return False

zipobj = zipfile.ZipFile(newZipFN,'w')

for infile in glob.glob( inShapefile.lower().replace(".shp",".*")):
   print infile
   zipobj.write(infile,os.path.basename(infile),zipfile.ZIP_DEFLATED)

zipobj.close()
return True

zipShapefile(wellsShapeFile,wellsZipFile)
print "done!"

2 thoughts on “Zipping a shapefile using python

  1. import zipfile
    import os
    import glob

    #os.getcwd()

    def zipShapefile(inShapefile):

    newZipFN = “zipped_”+inShapefile[:-3] + ‘zip’

    print ‘Starting to Zip ‘+inShapefile+’ to ‘+newZipFN

    print (os.path)
    if not (os.path.exists(inShapefile)):
    print inShapefile + ‘ Does Not Exist’
    return False

    if (os.path.exists(newZipFN)):
    print ‘Deleting ‘+newZipFN
    os.remove(newZipFN)

    if (os.path.exists(newZipFN)):
    print ‘Unable to Delete’+newZipFN
    return False

    zipobj = zipfile.ZipFile(newZipFN,’w’)

    for infile in glob.glob(inShapefile.replace(“.shp”,”.*”)):

    print infile
    zipobj.write(infile,os.path.basename(infile),zipfile.ZIP_DEFLATED)

    zipobj.close()
    return True

    print “done!”

    wellsShapeFile = “Clip_vilaine.shp”

    a = zipShapefile(wellsShapeFile)
    if a:
    print “Zipping done!”
    else:
    print “An error occurred during zipping.”

Comments are closed.