[Gdal-dev] Read shapefile from zip with python and OGR

Michael Ashbridge mtj.ashbridge at gmail.com
Sun Jul 22 06:07:07 EDT 2007


On 7/21/07, Sean Fulton <seanasy at gmail.com> wrote:
> I'd like to open a zip file with python and read a shapefile within the
> zip with OGR.  Some thing like this:
>
> import zipfile, ogr
>
> zip = zipfile.ZipFile('Zoning.zip', 'r')
> shape = zip.read('Zoning.shp')
> data=ogr.Open(shape)
>
> The above doesn't work. Is it because the shapefile driver needs access
> to the other files (.shx, .prj, .sbx, .dbf)? Is there a way to load
> them all manually?

Looks like you're sending a string of bytes to ogr.Open(), which
expects a filename. One way is to extract the contents of the zipfile
to a temporary directory and work from there:

#!/usr/bin/python

import os
import os.path
import tempfile
import zipfile

import ogr

zip = zipfile.ZipFile('Zoning.zip')
tempdir = tempfile.mkdtemp()

# Copy the zipped files to a temporary directory, preserving names.
for name in zip.namelist():
  data = zip.read(name)
  outfile = os.path.join(tempdir, name)
  f = open(outfile, 'w')
  f.write(data)
  f.close()

data = ogr.Open(os.path.join(tempdir, 'Zoning.shp'))
# More work here...

# Clean up after ourselves.
for file in os.listdir(tempdir):
  os.unlink(os.path.join(tempdir, file))
os.rmdir(tempdir)



More information about the Gdal-dev mailing list