[gdal-dev] Create new fields in existing shapefile with Python

Alexander Bruy alexander.bruy at gmail.com
Thu Apr 29 13:09:19 EDT 2010


Hi all,

when writing a script in Python for processing shapefiles I found
that I can add to the shapefile new fields with the same name many
times without any error or warning. But AFAIK all fields in shapefile
must have unique field names. Is this a bug and I need to post a
ticket? Or maybe I do something wrong?

Here is code

#!/usr/bin/env python
# -*- coding: utf-8 -*-

try:
  from osgeo import ogr
except ImportError:
  import ogr

import sys

def createField( inLayer, fieldName ):
  fieldDef = ogr.FieldDefn( fieldName, ogr.OFTReal )
  fieldDef.SetWidth( 12 )
  fieldDef.SetPrecision( 4 )
  if inLayer.CreateField( fieldDef ) != 0:
    print "Can't create field %s" % fieldDef.GetNameRef()
    return False
  return True

if __name__ == '__main__':
  args = sys.argv[ 1: ]
  filePath = args[ 0 ]
  inShape = ogr.Open( filePath, True )
  if inShape is None:
    print 'Unable to open shapefile', filePath
    sys.exit( 1 )

  inLayer = inShape.GetLayer( 0 )
  for i in range( 3 ):
    name = 'new_field'
    if not createField( inLayer, name ):
      print 'ERROR'
      sys.exit( 1 )

Script get from commandline path to any shapefile and adds to it
4 new fields with same name.
My software GDAL/OGR 1.6.3 with Python 2.5.2 under Linux.

Thanks
-- 
Alexander Bruy


More information about the gdal-dev mailing list