from qgis.core import QgsVectorFileWriter, QGis, QgsFields, QgsField, QgsGeometry, QgsFeature # Create a new shapefile fields = QgsFields() fields.append(QgsField('Name', QVariant.String)) fields.append(QgsField('Value', QVariant.Double)) crs = QgsCoordinateReferenceSystem(4326, QgsCoordinateReferenceSystem.EpsgCrsId) writer = QgsVectorFileWriter('test.shp', 'UTF-8', fields, QGis.WKBPoint, crs, 'ESRI Shapefile') # Write features to the new shapefile features = [] feature = QgsFeature(fields) feature.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(0, 0))) feature.setAttribute('Name', 'Point 1') feature.setAttribute('Value', 1.23) features.append(feature) feature = QgsFeature(fields) feature.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(1, 1))) feature.setAttribute('Name', 'Point 2') feature.setAttribute('Value', 4.56) features.append(feature) writer.addFeatures(features) del writer
from qgis.core import QgsVectorFileWriter, QgsVectorLayer, QgsFields, QgsField, QgsGeometry, QgsFeature # Load an existing layer layer = QgsVectorLayer('test.shp', 'test', 'ogr') if not layer.isValid(): raise ValueError('Layer not valid') # Update the layer fields = layer.fields() fields.append(QgsField('Count', QVariant.Int)) layer.startEditing() layer.dataProvider().addAttributes(fields) layer.commitChanges() # Write the layer to a GeoJSON file writer = QgsVectorFileWriter('test.geojson', 'UTF-8', fields, QgsWKBTypes.MultiPolygon, layer.sourceCrs(), 'GeoJSON') features = [] for feature in layer.getFeatures(): if feature.geometry().type() == QgsWkbTypes.PolygonGeometry: new_feature = QgsFeature(fields) new_feature.setGeometry(QgsGeometry(feature.geometry().constGet()).simplify(0.01, True)) new_feature.setAttributes(feature.attributes()) new_feature.setAttribute('Count', len(new_feature.geometry().asPolygon())) features.append(new_feature) writer.addFeatures(features) del writerIn both examples, we import the QgsVectorFileWriter class from the qgis.core package library. We then use it to create or update a layer and write it to a file in a specified format such as shapefile or GeoJSON. The first example creates a new point layer and adds two features to it, while the second example updates an existing layer by adding a new attribute field and simplifying the polygon geometries.