1

I am trying to develop a plugin to export selected features from a layer as shapefile.

I have a comboBox from which I can select features. After selecting features in comboBox, I tried following code but unable to get new shapefile of these particular features.

Initially I defined a location for exported shapefile by using push button.

    def select_output_file(self):
         filename, _filter = QFileDialog.getSaveFileName(
                   self.dlg, "Select   output file ","", '*.shp')
         self.dlg.lineEdit.setText(filename)

And then connect to this function:-

    def run(self):
           if self.first_start == True:
              self.first_start = False
              self.dlg = GetMapDialog()
              self.dlg.pushButton.clicked.connect(self.select_output_file)

And after getting features in comboBox, I tried this:

# show the dialog
    self.dlg.show()
    # Run the dialog event loop
    result = self.dlg.exec_()
    # See if OK was pressed
    if result:
      filename = self.dlg.lineEdit.text()
      with open(filename, 'w') as output_file:
          layer = selectedlayer ##U already add a main layer as selectedLayer
          selectedFeature = self.dlg.comboBox.currentText
          layer.select(selectedFeature)
          writer = QgsVectorFileWriter.writeAsVectorFormat(layer, output_file, 'utf-8', layer.crs(),'ESRI Shapefile', onlySelected=True)
          selected_layer = iface.addVectorLayer(output_file, '', 'ogr')
          del(writer)

After this, I got following error

Traceback (most recent call last): File "C:\Users/DELL/AppData/Roaming/QGIS/QGIS3\profiles\default/python/plugins\get_map\get_map.py", line 226, in run writer = QgsVectorFileWriter.writeAsVectorFormat(layer, output_file, 'utf-8', layer.crs(),'ESRI Shapefile', onlySelected=True) TypeError: QgsVectorFileWriter.writeAsVectorFormat(): arguments did not match any overloaded call: overload 1: argument 2 has unexpected type '_io.TextIOWrapper' overload 2: argument 2 has unexpected type '_io.TextIOWrapper' overload 3: argument 2 has unexpected type '_io.TextIOWrapper'

How can I overcome this error by which I can export a shapefile of a particular feature?

0

1 Answer 1

1

Looking at the API Docs suggests that writeAsVectorFormat expects the 2nd argument to be a string containing the file name not a file object, which would match your error message.

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.