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(…).

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

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)

driverForExtension

Returns the OGR driver name for a specified file extension.

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

param symExport

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

rtype

QgsVectorFileWriter.SymbologyExport

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

FeatureSymbology

Hidden

Int

NoError

NoSymbology

Original

PreferAlias

Set

SkipNonSpatialFormats

SortRecommended

String

SymbolLayerSymbology

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ΒΆ
FeatureSymbology = 1ΒΆ
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ΒΆ
NoSymbology = 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ΒΆ
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ΒΆ
SymbolLayerSymbology = 2ΒΆ
class SymbologyExportΒΆ

Bases: int

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: Union[QgsFeatureSink.Flags, QgsFeatureSink.Flag] = QgsFeatureSink.Flags()) boolΒΆ
Parameters
Return type

bool

addFeatureWithStyle(self, feature: QgsFeature, renderer: QgsFeatureRenderer, outputUnit: QgsUnitTypes.DistanceUnit = QgsUnitTypes.DistanceMeters) boolΒΆ

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

New in version 3.0.

Parameters
  • feature (QgsFeature) –

  • renderer (QgsFeatureRenderer) –

  • outputUnit (QgsUnitTypes.DistanceUnit = QgsUnitTypes.DistanceMeters) –

Return type

bool

addFeatures(self, features: Iterable[QgsFeature], flags: Union[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

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: QgsWkbTypes.Type, srs: QgsCoordinateReferenceSystem, transformContext: QgsCoordinateTransformContext, options: QgsVectorFileWriter.SaveVectorOptions, sinkFlags: Union[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

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

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: Union[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: Union[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: QgsVectorFileWriter.SymbologyExport)ΒΆ
Parameters

symExport (QgsVectorFileWriter.SymbologyExport) –

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: Union[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: Union[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) QgsVectorFileWriter.SymbologyExportΒΆ
Return type

QgsVectorFileWriter.SymbologyExport

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: QgsVectorFileWriter.SymbologyExport = QgsVectorFileWriter.NoSymbology, symbologyScale: float = 1, filterExtent: QgsRectangle = None, overrideGeometryType: QgsWkbTypes.Type = QgsWkbTypes.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 (QgsVectorFileWriter.SymbologyExport = QgsVectorFileWriter.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 (QgsWkbTypes.Type = QgsWkbTypes.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: QgsVectorFileWriter.SymbologyExport = QgsVectorFileWriter.NoSymbology, symbologyScale: float = 1, filterExtent: QgsRectangle = None, overrideGeometryType: QgsWkbTypes.Type = QgsWkbTypes.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
  • layer (QgsVectorLayer) – source layer to write

  • fileName (str) – file name to write to

  • transformContext (QgsCoordinateTransformContext) – coordinate transform context

  • options (QgsVectorFileWriter.SaveVectorOptions) – save options

  • newFilename (str = '') – potentially modified file name (output parameter)

  • newLayer (str = '') – potentially modified layer name (output parameter)

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.