I have a Shapefile layer in QGIS 2.6 with several polygons, each of which has data in over 100 fields. I need to create a new layer with all the same polygons, but with all their data fields blank (set to 0, Null or empty depending on the field type). Is there a quicker way of doing this than pressing delete on each field of each polygon one at a time, I would have to do this more than 1000 times this way.
You can enter the following code in the Python Console to clear ALL attributes to
NULL for a shapefile loaded into QGIS. Select the layer from the layers panel (Table of Contents) and run the code:
layer = qgis.utils.iface.activeLayer() layer.startEditing() for field in layer.dataProvider().attributeIndexes(): for feature in layer.getFeatures(): layer.changeAttributeValue(feature.id(), field, NULL) layer.commitChanges()
This was tested on QGIS 2.8.2.
In response to the comment by @Vince, the following code can be directly copied/pasted into the Python console and will change the values of attributes depending on the type of field (i.e.
0 for integer fields;
NULL for string fields; and an epoch of
1900-01-01 for a Date field):
layer = qgis.utils.iface.activeLayer() layer.startEditing() for field in layer.pendingFields(): if field.typeName() == 'Integer': name_int = field.name() for feature in layer.getFeatures(): feature[name_int] = '0' layer.updateFeature(feature) if field.typeName() == 'String': name_str = field.name() for feature in layer.getFeatures(): feature[name_str] = NULL layer.updateFeature(feature) if field.typeName() == 'Date': name_dat = field.name() for feature in layer.getFeatures(): feature[name_dat] = '1900-01-01' layer.updateFeature(feature) layer.commitChanges()
You can simply save it as a new file and tick the "Skip Attribute Creation" box in the "Save as..." dialog. It does exactly what it says.
There will be one numeric counter column named FID, apparently the Shapefile format requires at least one attribute? If you can, use something better, spatialite or geopackage.
Open the .dbf file with openoffice or others, and remove the data.
You can use python to loop over the files and remove all but the headers See dbf python module