Zipping a File Geodatabase using Python

Ever since the ever-popular post, Zipping a shapefile using python, came out, people have been asking (one person, yesterday) for a sample of how to zip a file geodatabase using python.

The key trick, as shown in line 17, is appending the basename of the file geodatabase (“nfg.gdb/” in my example) in front of each file as you write it to the zipfile.

UPDATE: WordPress messes with the spacing when I post code, making it difficult to post code that can just be copied & pasted and have work.  So I have posted a the code HERE for downloading.

import os
import zipfile
import glob

infile = "c:/temp/nfg.gdb"
outfile = "c:/temp/"
def zipFileGeodatabase(inFileGeodatabase, newZipFN):
if not (os.path.exists(inFileGeodatabase)):
return False

if (os.path.exists(newZipFN)):

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

for infile in glob.glob(inFileGeodatabase+"/*"):
zipobj.write(infile, os.path.basename(inFileGeodatabase)+"/"+os.path.basename(infile), zipfile.ZIP_DEFLATED)
print ("Zipping: "+infile)


return True



8 thoughts on “Zipping a File Geodatabase using Python

  1. Can you post the script with indents included? I’ve added the indentation, but keep getting an error on the zipobj variable. Thank you.

  2. Thanks for this post. This helped me out in a bind. I suggest one change on line 17 to better support platform independence by generating the path with os.path.join:

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

  3. When I use this script, I keep getting an error telling me that newZipFN isn’t identified. What could be causing that? Thank you!

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