3

I need to change field names of a shapefile to upper case using ogr. I want to do this automatically, versus calling out each field and replacing the name with upper case. When I try to implement using layer AlterFieldlDefn, I get a TypeError. Here is the code I am using:

Shapefile = r"C:\test.shp"
driver = ogr.GetDriverByName('ESRI Shapefile')
dataSource = driver.Open(Shapefile, 1) 

if dataSource is None:
    print 'Could not open %s' % (Shapefile)
else:
    print 'Opened %s' % (Shapefile)
    layer = dataSource.GetLayer()
    layer_defn = layer.GetLayerDefn()
    for i in range(layer_defn.GetFieldCount()):
        print layer_defn.GetFieldDefn(i).GetName()
        uppercase_name = layer_defn.GetFieldDefn(i).GetName().upper()
        layer.AlterFieldDefn(i, uppercase_name, 1)

The error I get is this:

TypeError: in method 'Layer_AlterFieldDefn', argument 3 of type 'OGRFieldDefnShadow

How do I correctly uses AlterFieldDefn to change the field names to upper case? I do not have ArcGIS 10.2, so AlterField_management is not an option.

  • You are starting a loop statement with your for statement but are not indenting for the lines after that. Is this the way you have it formatted? – artwork21 Feb 16 '16 at 21:32
  • My mistake, those next lines are indented. I corrected it above. – jtodd Feb 16 '16 at 22:16
1

Looks like you may be missing some steps. You need to use some additional methods like .CloneFieldDefn(), .SetName() method, and then use the .org.ALTER_NAME_FLAG value for the third parameter in the .AlterFieldDefn statement. See link below for code reference (lines 97-103).

https://github.com/stefanct/OGD_Wien_tools/blob/master/FAHRRADABSTELLANLAGEOGD.py

  • That reference did help to solve my problem. – jtodd Feb 17 '16 at 20:40
1

Although this post is quite old, I was facing a similar problem and sloved it like this:

layerDefn = layer.GetLayerDefn()
for i in range(layerDefn.GetFieldCount()):
    fieldDefn = layerDefn.GetFieldDefn(i)
    fieldName = fieldDefn.GetName()
    fieldDefn.SetName(fieldName.upper())

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.