6

Is it possible to delete a field in a shapefile using GDAL with python?

With gdal 2.1.3 (Ubuntu 16.04), I can only see a CreateField() method on the layer object. No similar functions to delete a field.

Searching around, I can only find a ticket discussing the possibility and related rfc35.

Is this function implemented and how to use it?

6

You can also use OGR SQL ALTER TABLE statement to DROP the column directly via ExecuteSQL():

from osgeo import gdal

ds = gdal.OpenEx("my_shp.shp", gdal.OF_VECTOR | gdal.OF_UPDATE)
ds.ExecuteSQL("ALTER TABLE my_shp DROP COLUMN my_field")
2

I usually see this done by creating a copy of the shapefile, but specifying which fields to include in the copy. Once a copy is made, it's easy enough to delete the original file and rename the copy.

Here is a simple non-python way. Otherwise, I think you should be able to create a solution based on this python example.

2

To delete a column from the attribute table of a shapefile, I used this:

dataSource = driver.Open("MyShapefile.shp", 1) 
layer = dataSource.GetLayer()
layer.DeleteField(4)   

where 4 is the index of the column I want to delete (starting from 0).

I hope it was what you asked.

  • We've just run into this problem. Calling DeleteField removes the field from the layer schema, but not from the features within the layer. The docstring says "This function should not be called while there are feature objects in existence that were obtained or created with the previous layer definition." – jon_two Sep 14 '18 at 11:35

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.