I have a Python script that adds an attribute field to a Shapefile if doesn't exist. This is easy to do with ArcGIS (graphically or via Python), but I'm looking for something that doesn't depend on ArcGIS.
I've looked at pyshp, but similarly there is no way to modify the schema after it has been created. I haven't had a try with shapefile (for Python), but I don't see this feature advertised. I also can't see how this can be done by tinkering with the DBF file via dbfpy.
Does anyone have any ideas?
I found a solution using OGR and thanks to help from a previous question. Here is a complete example:
from osgeo import ogr # Open a Shapefile, and get field names source = ogr.Open('my.shp', 1) layer = source.GetLayer() layer_defn = layer.GetLayerDefn() field_names = [layer_defn.GetFieldDefn(i).GetName() for i in range(layer_defn.GetFieldCount())] print len(field_names), 'MYFLD' in field_names # Add a new field new_field = ogr.FieldDefn('MYFLD', ogr.OFTInteger) layer.CreateField(new_field) # Close the Shapefile source = None
My problem was that I used
layer_defn.AddFieldDefn(new_field) rather than
layer.CreateField(new_field). Many thanks to the help, and sorry for not throughly checking for the similar other question.