Class: QgsVectorFileWriter

class qgis.core.QgsVectorFileWriter

Bases: QgsFeatureSink

A convenience class for writing vector files to disk. There are two possibilities how to use this class: 1. 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

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

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

Attributes

AppendToLayerAddFields

AppendToLayerNoNewFields

CanAddNewFieldsToExistingLayer

CanAddNewLayer

CanAppendToExistingLayer

CanDeleteLayer

Canceled

CreateOrOverwriteFile

CreateOrOverwriteLayer

ErrAttributeCreationFailed

ErrAttributeTypeUnsupported

ErrCreateDataSource

ErrCreateLayer

ErrDriverNotFound

ErrFeatureWriteFailed

ErrInvalidLayer

ErrProjection

FeatureSymbology

Hidden

Int

NoError

NoSymbology

Set

SkipNonSpatialFormats

SortRecommended

String

SymbolLayerSymbology

class ActionOnExistingFile

Bases: int

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

Bases: SetOption

QgsVectorFileWriter.BoolOption(QgsVectorFileWriter.BoolOption)

Parameters
  • docString (str) –

  • defaultValue (bool) –

CanAddNewFieldsToExistingLayer = 4
CanAddNewLayer = 1
CanAppendToExistingLayer = 2
CanDeleteLayer = 8
Canceled = 9
CreateOrOverwriteFile = 0
CreateOrOverwriteLayer = 1
class DriverDetails

Bases: sip.wrapper

QgsVectorFileWriter.DriverDetails(QgsVectorFileWriter.DriverDetails)

driverName
longName
class EditionCapabilities

Bases: sip.wrapper

QgsVectorFileWriter.EditionCapabilities(Union[QgsVectorFileWriter.EditionCapabilities, QgsVectorFileWriter.EditionCapability]) QgsVectorFileWriter.EditionCapabilities(QgsVectorFileWriter.EditionCapabilities)

class EditionCapability

Bases: int

ErrAttributeCreationFailed = 5
ErrAttributeTypeUnsupported = 4
ErrCreateDataSource = 2
ErrCreateLayer = 3
ErrDriverNotFound = 1
ErrFeatureWriteFailed = 7
ErrInvalidLayer = 8
ErrProjection = 6
FeatureSymbology = 1
class FieldValueConverter

Bases: sip.wrapper

Constructor

QgsVectorFileWriter.FieldValueConverter(QgsVectorFileWriter.FieldValueConverter)

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

New in version 2.16.

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

Bases: sip.wrapper

QgsVectorFileWriter.FilterFormatDetails(QgsVectorFileWriter.FilterFormatDetails)

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

Bases: Option

QgsVectorFileWriter.HiddenOption(QgsVectorFileWriter.HiddenOption)

Parameters

value (str) –

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

Bases: Option

QgsVectorFileWriter.IntOption(QgsVectorFileWriter.IntOption)

Parameters
  • docString (str) –

  • defaultValue (int) –

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)

Bases: sip.wrapper

QgsVectorFileWriter.Option(QgsVectorFileWriter.Option)

Parameters
docString
type
class OptionType

Bases: int

class SaveVectorOptions

Bases: sip.wrapper

Constructor

QgsVectorFileWriter.SaveVectorOptions(QgsVectorFileWriter.SaveVectorOptions)

Options to pass to writeAsVectorFormat()

New in version 3.0.

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

Bases: Option

QgsVectorFileWriter.SetOption(QgsVectorFileWriter.SetOption)

Parameters
  • docString (str) –

  • values (Iterable[str]) –

  • defaultValue (str) –

  • allowNone (bool = False) –

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

Bases: Option

QgsVectorFileWriter.StringOption(QgsVectorFileWriter.StringOption)

Parameters
  • docString (str) –

  • defaultValue (str = '') –

defaultValue
SymbolLayerSymbology = 2
class SymbologyExport

Bases: int

class VectorFormatOption

Bases: int

class VectorFormatOptions

Bases: sip.wrapper

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

class WriterError

Bases: int

addFeature(self, feature: QgsFeature, flags: Union[QgsFeatureSink.Flags, QgsFeatureSink.Flag] = 0) → 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
Return type

bool

addFeatures(self, features: Iterable[QgsFeature], flags: Union[QgsFeatureSink.Flags, QgsFeatureSink.Flag] = 0) → 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

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

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 – pointer to buffer fo error message

  • 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)

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 – pointer to buffer fo error message

  • 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.

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 – pointer to buffer fo error message

New in version 3.0.

Return type

Tuple[QgsVectorFileWriter.WriterError, str]