|

PyQGIS: Create a Shapefile

In this tutorial, we’ll walk through how to create a shapefile from scratch with the QGIS Python (PyQGIS) API.

You shouldn’t need to do this, but if you’re running into problems where functions don’t show up you can import the qgis module at the beginning. This usually isn’t a problem but there have been a couple of times that I’ve had to do this.

import qgis

The first step is to create a list of fields we want to include in the attribute table of our shapefile. QgsFields() creates a list of fields, we then append a QgsField() to the fields list for every field we want to include. QgsField takes the name of the field as a string and field type as a QVariant.

# create fields
layerFields = QgsFields()
layerFields.append(QgsField('ID', QVariant.Int))
layerFields.append(QgsField('Value', QVariant.Double))
layerFields.append(QgsField('Name', QVariant.String))

Now define the file path for the new shapefile. The new shapefile is created with a single line of code using QgsVectorFileWriter. We need to pass the file path, file encoding, fields (from the code above), geometry type, CRS, and driver as arguments to QgsVectorFileWriter. The function returns an object (defined as writer in the code) which can write/add features to the shapefile. Note: the CRS used here is NAD 1983 UTM Zone 11 N.

fn = 'C:/temp/newpoints.shp'
writer = QgsVectorFileWriter(fn, 'UTF-8', layerFields, QgsWkbTypes.Point, QgsCoordinateReferenceSystem('EPSG:26912'), 'ESRI Shapefile')

After the writer is created, the next step is to use the writer to add features to the shapefile. For each feature we need to set the geometry (in this case a point), set the attribute values, then add it to the vector layer.

First, create an empty QgsFeature().

feat = QgsFeature()

Second, create a point and use it to set the feature geometry.

feat.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(455618, 4632221)))

Third, set the attribute values.

feat.setAttributes([1, 1.1, 'one'])

Finally, add the feature to the layer.

writer.addFeature(feat)

After all the desired features are added the layer can be added to the interface and the writer can be deleted.

layer = iface.addVectorLayer(fn, '', 'ogr')
del(writer)

Here’s the final code. Watch the video below for a step-by-step demonstration.

# create fields
layerFields = QgsFields()
layerFields.append(QgsField('ID', QVariant.Int))
layerFields.append(QgsField('Value', QVariant.Double))
layerFields.append(QgsField('Name', QVariant.String))

fn = 'C:/temp/newpoints.shp'
writer = QgsVectorFileWriter(fn, 'UTF-8', layerFields,\
QgsWkbTypes.Point,\
QgsCoordinateReferenceSystem('EPSG:26912'),\
'ESRI Shapefile')

feat = QgsFeature()
feat.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(455618, 4632221)))
feat.setAttributes([1, 1.1, 'one'])
writer.addFeature(feat)

layer = iface.addVectorLayer(fn, '', 'ogr')

del(writer)

Similar Posts