4

I'm attempting to save a polygon created in a scratch layer to a shapefile. The Python code below is a simplified example. Note the questions: Saving layer as shapefile using PyQGIS and Setting QgsVectorFileWriter.SaveVectorOptions for QGIS 3 provided some of the help, which I'm including in this post for future reference,

# Attach libraries
from qgis.core import * # attach main QGIS library
from qgis.utils import * # attach main python library
import os # attach operating system library

# Set the working directory
wd = "C:/test" # Set work directory
os.chdir(wd) # Change the directory

# Set a variable for the current project instance
  Prj = QgsProject().instance() # Object for current project

# Save the project to this file name
pnm = "Test.qgs" # Project file name
pnm = wd + "/" + pnm # Concat. with path
Prj.write(pnm) # Save the project

# Create an array [] object with the polygon vertices
vrtcs = []
vrtcs.append(QgsPointXY(396100,8969000))
vrtcs.append(QgsPointXY(396100,8973900))
vrtcs.append(QgsPointXY(397900,8973900))
vrtcs.append(QgsPointXY(397900,8969000))

# Create a polygon from the vertices
ply_01 = QgsGeometry.fromPolygonXY([vrtcs])

# Create a feature object then append the polygon into 
ftr = QgsFeature()
ftr.setGeometry(ply_01)
print(ftr.geometry())

# Create a layer for the feature and add to the project
lyr = QgsVectorLayer('Polygon?crs=epsg:29194','Test',"memory")
Prj.addMapLayers([lyr])

# Make the layer editable, add the feature and save
lyr.startEditing()
lyr.addFeature(ftr)
lyr.commitChanges()

# Save as a shapefile
Fl_ou = 'Test.shp'
Fl_ou = wd + '/' + Fl_ou
writer = QgsVectorFileWriter(lry, Fl_ou,'urf-8','ESRI Shapefile')

When I execute the last line I get the following error "NameError: name 'lry' is not defined".

However, when I enter type(lyr) into the console it recognizes the variable lyr as a <class 'qgis._core.QgsVectorLayer'> so I am unsure why I'm getting the not defined error.

3
  • You are correct about the typo - but when corrected to lyr now get the error 'TypeError: QgsVectorFileWriter(): argument 1 has unexpected type 'QgsVectorLayer''. I'm guessing the first argument was expecting a string, not an object but when I change argument 1 to 'Test' (the name of the layer) the console reports a new error 'QgsVectorFileWriter(): argument 3 has unexpected type 'str'. Nothing like a nice game of snakes and ladders! Any ideas? Sep 15, 2020 at 8:50
  • 2
    Which QGIS version do you have? 'urf-8' should be 'utf-8'
    – BERA
    Sep 15, 2020 at 9:05

1 Answer 1

6

Use writeAsVectorFormatV2 method of QgsVectorFileWriter class in version 3.10.3+. (Tested in QGIS 3.12)

# Attach libraries
from qgis.core import * # attach main QGIS library
from qgis.utils import * # attach main python library
import os # attach operating system library

# Set the working directory
wd = "C:/test" # Set work directory
os.chdir(wd) # Change the directory

# Set a variable for the current project instance
Prj = QgsProject().instance() # Object for current project

# Save the project to this file name
pnm = "Test.qgs" # Project file name
pnm = wd + "/" + pnm # Concat. with path
Prj.write(pnm) # Save the project

# Create an array [] object with the polygon vertices
vrtcs = []
vrtcs.append(QgsPointXY(396100,8969000))
vrtcs.append(QgsPointXY(396100,8973900))
vrtcs.append(QgsPointXY(397900,8973900))
vrtcs.append(QgsPointXY(397900,8969000))

# Create a polygon from the vertices
ply_01 = QgsGeometry.fromPolygonXY([vrtcs])

# Create a feature object then append the polygon into 
ftr = QgsFeature()
ftr.setGeometry(ply_01)
print(ftr.geometry())

# Create a layer for the feature and add to the project
lyr = QgsVectorLayer('Polygon?crs=epsg:29194','Test',"memory")
Prj.addMapLayers([lyr])

# Make the layer editable, add the feature and save
lyr.startEditing()
lyr.addFeature(ftr)
lyr.commitChanges()

# Save as a shapefile
Fl_ou = 'Test.shp'
Fl_ou = wd + '/' + Fl_ou

options = QgsVectorFileWriter.SaveVectorOptions()
options.driverName = "ESRI Shapefile"

QgsVectorFileWriter.writeAsVectorFormatV2(lyr, Fl_ou, QgsCoordinateTransformContext(), options)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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