Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a problem with the examples in the book "Python Geospatial Development". I can't write to the PostgreSQL database polygons from TM_WORLD_BORDERS (Chapter 7, page 202 in book). Code:

src_file = os.path.join('TM_WORLD_BORDERS-0.3.shp')

shapefile = osgeo.ogr.Open(src_file)
layer = shapefile.GetLayer(0)

for i in range(layer.GetFeatureCount()):
    feature = layer.GetFeature(i)
    name = feature.GetField('NAME').decode('Latin-1')
    geometry = feature.GetGeometryRef()

    wkt = geometry.ExportToWkt()

    cursor.execute('INSERT INTO countries (name, outline) '+
                   'VALUES (%s, ST_PolygonFromText(%s, 4326))' +
                   '', (name.encode('utf8'), wkt))


Only 30 out of 246 polygons are written. But the geometry.IsValid() function shows that 242 country polygons are valid.

share|improve this question

I think it blows up on the first invalid one, you need to use the isvalid check as you go

share|improve this answer
I think that is not the case. In my view the problem as a function of ST_PolygonFromText () which in most cases, returns Null instead of the binary representation of the countrie-polygons. But this polygons are valid – Kirill Krasov Nov 30 '11 at 17:53

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.