Class: QgsVectorFileWriter

class qgis.core.QgsVectorFileWriter

Bases: QgsFeatureSink

A convenience class for writing vector layers to disk based formats (e.g. Shapefiles, GeoPackage).

There are two possibilities how to use this class:

  1. A static call to QgsVectorFileWriter.writeAsVectorFormat(…) which saves the whole vector layer.

  2. Create an instance of the class and issue calls to addFeature(…).

Enums

SymbologyExport

alias of FeatureSymbologyExport

Methods

addFeature

param feature:

addFeatureWithStyle

Adds a feature to the currently opened data source, using the style from a specified renderer.

addFeatures

param features:

areThereNewFieldsToCreate

Returns whether there are among the attributes specified some that do not exist yet in the layer

capabilities

Returns the capabilities supported by the writer.

convertCodecNameForEncodingOption

Converts codec name to string passed to ENCODING layer creation option of OGR Shapefile

create

Create a new vector file writer.

defaultDatasetOptions

Returns a list of the default dataset options for a specified driver.

defaultLayerOptions

Returns a list of the default layer options for a specified driver.

deleteShapeFile

Delete a shapefile (and its accompanying shx / dbf / prj / qix / qpj / cpg / sbn / sbx / idm / ind)

driver

Returns the GDAL (short) driver name associated with the output file.

driverForExtension

Returns the OGR driver name for a specified file extension.

driverLongName

Returns the GDAL long driver name associated with the output file.

driverMetadata

param driverName:

editionCapabilities

Returns edition capabilities for an existing dataset name.

errorMessage

Retrieves error message

fileFilterString

Returns filter string that can be used for dialogs.

filterForDriver

Creates a filter for an OGR driver key

hasError

Checks whether there were any errors in constructor

lastError

rtype:

str

ogrDriverList

Returns the driver list that can be used for dialogs.

setSymbologyExport

Sets the feature symbology export handling for the writer.

setSymbologyScale

Set reference scale for output.

supportedFiltersAndFormats

Returns a list or pairs, with format filter string as first element and OGR format key as second element.

supportedFormatExtensions

Returns a list of file extensions for supported formats, e.g "shp", "gpkg".

supportsFeatureStyles

Returns True if the specified driverName supports feature styles.

symbologyExport

Returns the feature symbology export handling for the writer.

symbologyScale

Returns the reference scale for output.

targetLayerExists

Returns whether the target layer already exists.

writeAsVectorFormat

Write contents of vector layer to an (OGR supported) vector format

writeAsVectorFormatV2

Writes a layer out to a vector file.

writeAsVectorFormatV3

Writes a layer out to a vector file.

Attributes

AppendToLayerAddFields

AppendToLayerNoNewFields

CanAddNewFieldsToExistingLayer

CanAddNewLayer

CanAppendToExistingLayer

CanDeleteLayer

Canceled

CreateOrOverwriteFile

CreateOrOverwriteLayer

ErrAttributeCreationFailed

ErrAttributeTypeUnsupported

ErrCreateDataSource

ErrCreateLayer

ErrDriverNotFound

ErrFeatureWriteFailed

ErrInvalidLayer

ErrProjection

ErrSavingMetadata

Hidden

Int

NoError

Original

PreferAlias

Set

SkipNonSpatialFormats

SortRecommended

String

SupportsMultipleLayers

class ActionOnExistingFile

Bases: int

AppendToLayerAddFields = 3
AppendToLayerNoNewFields = 2
class BoolOption(docString: str, defaultValue: bool)
class BoolOption(QgsVectorFileWriter.BoolOption)

Bases: SetOption

CanAddNewFieldsToExistingLayer = 4
CanAddNewLayer = 1
CanAppendToExistingLayer = 2
CanDeleteLayer = 8
Canceled = 10
CreateOrOverwriteFile = 0
CreateOrOverwriteLayer = 1
class DriverDetails
class DriverDetails(QgsVectorFileWriter.DriverDetails)

Bases: sip.wrapper

driverName
longName
class EditionCapabilities
class EditionCapabilities(Union[QgsVectorFileWriter.EditionCapabilities, QgsVectorFileWriter.EditionCapability])
class EditionCapabilities(QgsVectorFileWriter.EditionCapabilities)

Bases: sip.wrapper

class EditionCapability

Bases: int

ErrAttributeCreationFailed = 5
ErrAttributeTypeUnsupported = 4
ErrCreateDataSource = 2
ErrCreateLayer = 3
ErrDriverNotFound = 1
ErrFeatureWriteFailed = 7
ErrInvalidLayer = 8
ErrProjection = 6
ErrSavingMetadata = 9
class FieldNameSource

Bases: int

class FieldValueConverter

Bases: sip.wrapper

Interface to convert raw field values to their user-friendly value.

New in version 2.16.

QgsVectorFileWriter.FieldValueConverter() Constructor

QgsVectorFileWriter.FieldValueConverter(QgsVectorFileWriter.FieldValueConverter)

clone(self) QgsVectorFileWriter.FieldValueConverter

Creates a clone of the FieldValueConverter.

Return type:

QgsVectorFileWriter.FieldValueConverter

convert(self, fieldIdxInLayer: int, value: Any) Any

Convert the provided value, for field fieldIdxInLayer. Default implementation will return provided value unmodified.

Parameters:
  • fieldIdxInLayer (int) – field index

  • value (Any) – original raw value

Return type:

Any

Returns:

possibly modified value.

fieldDefinition(self, field: QgsField) QgsField

Returns a possibly modified field definition. Default implementation will return provided field unmodified.

Parameters:

field (QgsField) – original field definition

Return type:

QgsField

Returns:

possibly modified field definition

class FilterFormatDetails
class FilterFormatDetails(QgsVectorFileWriter.FilterFormatDetails)

Bases: sip.wrapper

driverName
filterString
globs
Hidden = 3
class HiddenOption(value: str)
class HiddenOption(QgsVectorFileWriter.HiddenOption)

Bases: Option

mValue
Int = 2
class IntOption(docString: str, defaultValue: int)
class IntOption(QgsVectorFileWriter.IntOption)

Bases: Option

defaultValue
class MetaData

Bases: sip.wrapper

Constructor for MetaData

QgsVectorFileWriter.MetaData(longName: str, trLongName: str, glob: str, ext: str, driverOptions: object, layerOptions: object, compulsoryEncoding: str = ‘’)

QgsVectorFileWriter.MetaData(QgsVectorFileWriter.MetaData)

compulsoryEncoding
driverOptions
ext
glob
layerOptions
longName
trLongName
NoError = 0
class Option(docString: str, type: QgsVectorFileWriter.OptionType)
class Option(QgsVectorFileWriter.Option)

Bases: sip.wrapper

docString
type
class OptionType

Bases: int

Original = 0
PreferAlias = 1
class SaveVectorOptions

Bases: sip.wrapper

Options to pass to writeAsVectorFormat()

New in version 3.0.

QgsVectorFileWriter.SaveVectorOptions() Constructor

QgsVectorFileWriter.SaveVectorOptions(QgsVectorFileWriter.SaveVectorOptions)

actionOnExistingFile
attributes
attributesExportNames
ct
datasourceOptions
driverName
feedback
fieldNameSource
fieldValueConverter
fileEncoding
filterExtent
forceMulti
includeZ
layerMetadata
layerName
layerOptions
onlySelectedFeatures
overrideGeometryType
saveMetadata
skipAttributeCreation
symbologyExport
symbologyScale
Set = 0
class SetOption(docString: str, values: Iterable[str], defaultValue: str, allowNone: bool = False)
class SetOption(QgsVectorFileWriter.SetOption)

Bases: Option

allowNone
defaultValue
values
SkipNonSpatialFormats = 4
SortRecommended = 2
String = 1
class StringOption(docString: str, defaultValue: str = '')
class StringOption(QgsVectorFileWriter.StringOption)

Bases: Option

defaultValue
SupportsMultipleLayers = 8
SymbologyExport

alias of FeatureSymbologyExport

class VectorFormatOption

Bases: int

class VectorFormatOptions
class VectorFormatOptions(Union[QgsVectorFileWriter.VectorFormatOptions, QgsVectorFileWriter.VectorFormatOption])
class VectorFormatOptions(QgsVectorFileWriter.VectorFormatOptions)

Bases: sip.wrapper

class WriterError

Bases: int

addFeature(self, feature: QgsFeature, flags: QgsFeatureSink.Flags | QgsFeatureSink.Flag = QgsFeatureSink.Flags()) bool
Parameters:
Return type:

bool

addFeatureWithStyle(self, feature: QgsFeature, renderer: QgsFeatureRenderer, outputUnit: Qgis.DistanceUnit = Qgis.DistanceUnit.Meters) bool

Adds a feature to the currently opened data source, using the style from a specified renderer.

New in version 3.0.

Parameters:
Return type:

bool

addFeatures(self, features: Iterable[QgsFeature], flags: QgsFeatureSink.Flags | QgsFeatureSink.Flag = QgsFeatureSink.Flags()) bool
Parameters:
Return type:

bool

areThereNewFieldsToCreate(datasetName: str, layerName: str, layer: QgsVectorLayer, attributes: Iterable[int]) bool

Returns whether there are among the attributes specified some that do not exist yet in the layer

New in version 3.0.

Parameters:
  • datasetName (str) –

  • layerName (str) –

  • layer (QgsVectorLayer) –

  • attributes (Iterable[int]) –

Return type:

bool

capabilities(self) Qgis.VectorFileWriterCapabilities

Returns the capabilities supported by the writer.

New in version 3.32.

Return type:

Qgis.VectorFileWriterCapabilities

convertCodecNameForEncodingOption(codecName: str) str

Converts codec name to string passed to ENCODING layer creation option of OGR Shapefile

Parameters:

codecName (str) –

Return type:

str

create(fileName: str, fields: QgsFields, geometryType: Qgis.WkbType, srs: QgsCoordinateReferenceSystem, transformContext: QgsCoordinateTransformContext, options: QgsVectorFileWriter.SaveVectorOptions, sinkFlags: QgsFeatureSink.SinkFlags | QgsFeatureSink.SinkFlag = QgsFeatureSink.SinkFlags(), newFilename: str = '', newLayer: str = '') QgsVectorFileWriter

Create a new vector file writer.

Parameters:

New in version 3.10.3.

Return type:

QgsVectorFileWriter

defaultDatasetOptions(driverName: str) List[str]

Returns a list of the default dataset options for a specified driver.

Parameters:

driverName (str) – name of OGR driver

New in version 3.0.

Return type:

List[str]

defaultLayerOptions(driverName: str) List[str]

Returns a list of the default layer options for a specified driver.

Parameters:

driverName (str) – name of OGR driver

New in version 3.0.

Return type:

List[str]

deleteShapeFile(fileName: str) bool

Delete a shapefile (and its accompanying shx / dbf / prj / qix / qpj / cpg / sbn / sbx / idm / ind)

Parameters:

fileName (str) – /path/to/file.shp

Return type:

bool

Returns:

bool True if the file was deleted successfully

driver(self) str

Returns the GDAL (short) driver name associated with the output file.

See also

driverLongName()

New in version 3.32.

Return type:

str

driverForExtension(extension: str) str

Returns the OGR driver name for a specified file extension. E.g. the driver name for the “.shp” extension is “ESRI Shapefile”. If no suitable drivers are found then an empty string is returned.

New in version 3.0.

Parameters:

extension (str) –

Return type:

str

driverLongName(self) str

Returns the GDAL long driver name associated with the output file.

See also

driver()

New in version 3.32.

Return type:

str

driverMetadata(driverName: str, driverMetadata: QgsVectorFileWriter.MetaData) bool
Parameters:
Return type:

bool

editionCapabilities(datasetName: str) QgsVectorFileWriter.EditionCapabilities

Returns edition capabilities for an existing dataset name.

New in version 3.0.

Parameters:

datasetName (str) –

Return type:

QgsVectorFileWriter.EditionCapabilities

errorMessage(self) str

Retrieves error message

Return type:

str

fileFilterString(options: QgsVectorFileWriter.VectorFormatOptions | QgsVectorFileWriter.VectorFormatOption = QgsVectorFileWriter.SortRecommended) str

Returns filter string that can be used for dialogs.

The options argument can be used to control the sorting and filtering of returned drivers.

Parameters:

options (Union[QgsVectorFileWriter.VectorFormatOptions) –

Return type:

str

filterForDriver(driverName: str) str

Creates a filter for an OGR driver key

Parameters:

driverName (str) –

Return type:

str

hasError(self) QgsVectorFileWriter.WriterError

Checks whether there were any errors in constructor

Return type:

QgsVectorFileWriter.WriterError

lastError(self) str
Return type:

str

ogrDriverList(options: QgsVectorFileWriter.VectorFormatOptions | QgsVectorFileWriter.VectorFormatOption = QgsVectorFileWriter.SortRecommended) List[QgsVectorFileWriter.DriverDetails]

Returns the driver list that can be used for dialogs. It contains all OGR drivers plus some additional internal QGIS driver names to distinguish between more supported formats of the same OGR driver.

The returned list consists of structs containing the driver long name (e.g. user-friendly display name for the format) and internal driver short name.

The options argument can be used to control the sorting and filtering of returned drivers.

Parameters:

options (Union[QgsVectorFileWriter.VectorFormatOptions) –

Return type:

List[QgsVectorFileWriter.DriverDetails]

setSymbologyExport(self, symExport: Qgis.FeatureSymbologyExport)

Sets the feature symbology export handling for the writer.

Parameters:

symExport (Qgis.FeatureSymbologyExport) –

setSymbologyScale(self, scale: float)

Set reference scale for output. The scale value indicates the scale denominator, e.g. 1000.0 for a 1:1000 map.

See also

symbologyScale()

New in version 3.0.

Parameters:

scale (float) –

supportedFiltersAndFormats(options: QgsVectorFileWriter.VectorFormatOptions | QgsVectorFileWriter.VectorFormatOption = QgsVectorFileWriter.SortRecommended) List[QgsVectorFileWriter.FilterFormatDetails]

Returns a list or pairs, with format filter string as first element and OGR format key as second element.

The options argument can be used to control the sorting and filtering of returned formats.

Parameters:

options (Union[QgsVectorFileWriter.VectorFormatOptions) –

Return type:

List[QgsVectorFileWriter.FilterFormatDetails]

supportedFormatExtensions(options: QgsVectorFileWriter.VectorFormatOptions | QgsVectorFileWriter.VectorFormatOption = QgsVectorFileWriter.SortRecommended) List[str]

Returns a list of file extensions for supported formats, e.g “shp”, “gpkg”.

The options argument can be used to control the sorting and filtering of returned formats.

New in version 3.0.

Parameters:

options (Union[QgsVectorFileWriter.VectorFormatOptions) –

Return type:

List[str]

supportsFeatureStyles(driverName: str) bool

Returns True if the specified driverName supports feature styles.

The driverName argument must be a valid GDAL driver name.

New in version 3.0.

Parameters:

driverName (str) –

Return type:

bool

symbologyExport(self) Qgis.FeatureSymbologyExport

Returns the feature symbology export handling for the writer.

Return type:

Qgis.FeatureSymbologyExport

symbologyScale(self) float

Returns the reference scale for output. The scale value indicates the scale denominator, e.g. 1000.0 for a 1:1000 map.

New in version 3.0.

Return type:

float

targetLayerExists(datasetName: str, layerName: str) bool

Returns whether the target layer already exists.

New in version 3.0.

Parameters:
  • datasetName (str) –

  • layerName (str) –

Return type:

bool

writeAsVectorFormat(layer: QgsVectorLayer, fileName: str, fileEncoding: str, destCRS: QgsCoordinateReferenceSystem = QgsCoordinateReferenceSystem(), driverName: str = '', onlySelected: bool = False, datasourceOptions: Iterable[str] = [], layerOptions: Iterable[str] = [], skipAttributeCreation: bool = False, newFilename: str = '', symbologyExport: Qgis.FeatureSymbologyExport = Qgis.FeatureSymbologyExport.NoSymbology, symbologyScale: float = 1, filterExtent: QgsRectangle = None, overrideGeometryType: Qgis.WkbType = Qgis.WkbType.Unknown, forceMulti: bool = False, includeZ: bool = False, attributes: Iterable[int] = [], fieldValueConverter: QgsVectorFileWriter.FieldValueConverter = None) Tuple[QgsVectorFileWriter.WriterError, str]

Write contents of vector layer to an (OGR supported) vector format

Parameters:
  • layer (QgsVectorLayer) – layer to write

  • fileName (str) – file name to write to

  • fileEncoding (str) – encoding to use

  • destCRS (QgsCoordinateReferenceSystem = QgsCoordinateReferenceSystem()) – CRS to reproject exported geometries to, or invalid CRS for no reprojection

  • driverName (str = '') – OGR driver to use

  • onlySelected (bool = False) – write only selected features of layer

  • errorMessage – will be set to the error message text, if an error occurs while writing the layer

  • datasourceOptions (Iterable[str] = []) – list of OGR data source creation options

  • layerOptions (Iterable[str] = []) – list of OGR layer creation options

  • skipAttributeCreation (bool = False) – only write geometries

  • newFilename (str = '') – QString pointer which will contain the new file name created (in case it is different to fileName).

  • symbologyExport (Qgis.FeatureSymbologyExport = Qgis.FeatureSymbologyExport.NoSymbology) – symbology to export

  • symbologyScale (float = 1) – scale of symbology

  • filterExtent (QgsRectangle = None) – if not None, only features intersecting the extent will be saved (added in QGIS 2.4)

  • overrideGeometryType (Qgis.WkbType = Qgis.WkbType.Unknown) – set to a valid geometry type to override the default geometry type for the layer. This parameter allows for conversion of geometryless tables to null geometries, etc (added in QGIS 2.14)

  • forceMulti (bool = False) – set to True to force creation of multi* geometries (added in QGIS 2.14)

  • includeZ (bool = False) – set to True to include z dimension in output. This option is only valid if overrideGeometryType is set. (added in QGIS 2.14)

  • attributes (Iterable[int] = []) – attributes to export (empty means all unless skipAttributeCreation is set)

  • fieldValueConverter (QgsVectorFileWriter.FieldValueConverter = None) – field value converter (added in QGIS 2.16)

Deprecated since version Use: writeAsVectorFormatV2() instead.

writeAsVectorFormat(layer: QgsVectorLayer, fileName: str, fileEncoding: str, ct: QgsCoordinateTransform, driverName: str = ‘’, onlySelected: bool = False, datasourceOptions: Iterable[str] = [], layerOptions: Iterable[str] = [], skipAttributeCreation: bool = False, newFilename: str = ‘’, symbologyExport: Qgis.FeatureSymbologyExport = Qgis.FeatureSymbologyExport.NoSymbology, symbologyScale: float = 1, filterExtent: QgsRectangle = None, overrideGeometryType: Qgis.WkbType = Qgis.WkbType.Unknown, forceMulti: bool = False, includeZ: bool = False, attributes: Iterable[int] = [], fieldValueConverter: QgsVectorFileWriter.FieldValueConverter = None) -> Tuple[QgsVectorFileWriter.WriterError, str] Writes a layer out to a vector file.

Parameters:
  • layer – layer to write

  • fileName – file name to write to

  • fileEncoding – encoding to use

  • ct – coordinate transform to reproject exported geometries with, or invalid transform for no transformation

  • driverName – OGR driver to use

  • onlySelected – write only selected features of layer

  • errorMessage – will be set to the error message text, if an error occurs while writing the layer

  • datasourceOptions – list of OGR data source creation options

  • layerOptions – list of OGR layer creation options

  • skipAttributeCreation – only write geometries

  • newFilename – QString pointer which will contain the new file name created (in case it is different to fileName).

  • symbologyExport – symbology to export

  • symbologyScale – scale of symbology

  • filterExtent – if not None, only features intersecting the extent will be saved (added in QGIS 2.4)

  • overrideGeometryType – set to a valid geometry type to override the default geometry type for the layer. This parameter allows for conversion of geometryless tables to null geometries, etc (added in QGIS 2.14)

  • forceMulti – set to True to force creation of multi* geometries (added in QGIS 2.14)

  • includeZ – set to True to include z dimension in output. This option is only valid if overrideGeometryType is set. (added in QGIS 2.14)

  • attributes – attributes to export (empty means all unless skipAttributeCreation is set)

  • fieldValueConverter – field value converter (added in QGIS 2.16)

New in version 2.2.

Deprecated since version Use: writeAsVectorFormatV2() instead.

writeAsVectorFormat(layer: QgsVectorLayer, fileName: str, options: QgsVectorFileWriter.SaveVectorOptions, newFilename: str = ‘’) -> Tuple[QgsVectorFileWriter.WriterError, str] Writes a layer out to a vector file.

Parameters:
  • layer – source layer to write

  • fileName – file name to write to

  • options – options.

  • newFilename – QString pointer which will contain the new file name created (in case it is different to fileName).

  • errorMessage – will be set to the error message text, if an error occurs while writing the layer

New in version 3.0.

Deprecated since version Use: writeAsVectorFormatV2() instead.

Return type:

Tuple[QgsVectorFileWriter.WriterError, str]

writeAsVectorFormatV2(layer: QgsVectorLayer, fileName: str, transformContext: QgsCoordinateTransformContext, options: QgsVectorFileWriter.SaveVectorOptions, newFilename: str = '', newLayer: str = '') Tuple[QgsVectorFileWriter.WriterError, str]

Writes a layer out to a vector file.

Parameters:
Return type:

Tuple[QgsVectorFileWriter.WriterError, str]

Returns:

  • Error message code, or QgsVectorFileWriter.NoError if the write operation was successful

  • errorMessage: will be set to the error message text, if an error occurs while writing the layer

Deprecated since version QGIS: 3.20 use writeAsVectorFormatV3 instead

writeAsVectorFormatV3(layer: QgsVectorLayer, fileName: str, transformContext: QgsCoordinateTransformContext, options: QgsVectorFileWriter.SaveVectorOptions) Tuple[QgsVectorFileWriter.WriterError, str, str, str]

Writes a layer out to a vector file.

Parameters:
  • layer (QgsVectorLayer) – source layer to write

  • fileName (str) – file name to write to

  • transformContext (QgsCoordinateTransformContext) – coordinate transform context

  • options (QgsVectorFileWriter.SaveVectorOptions) – save options

  • newFilename – potentially modified file name (output parameter)

  • errorMessage – will be set to the error message text, if an error occurs while writing the layer

Return type:

Tuple[QgsVectorFileWriter.WriterError, str, str, str]

Returns:

  • Error message code, or QgsVectorFileWriter.NoError if the write operation was successful

  • newLayer: potentially modified layer name (output parameter)

New in version 3.20.