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.


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

| 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 clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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