7

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.

Taras
35.8k5 gold badges77 silver badges151 bronze badges
asked Sep 15, 2020 at 7:41
2
  • 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? Commented Sep 15, 2020 at 8:50
  • 2
    Which QGIS version do you have? 'urf-8' should be 'utf-8' Commented Sep 15, 2020 at 9:05

2 Answers 2

10

Use writeAsVectorFormatV2 method of QgsVectorFileWriter class.

# 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)
answered Sep 15, 2020 at 11:31
-2

I understand this is an old post, but I developed a plugin that saves all vector layers as .gpkg. All temporary layers are automatically made permanent. Want to share if it can be of use: https://plugins.qgis.org/plugins/SaveAllScript/

answered Jun 29, 2023 at 16:32
1
  • 3
    This is not answering the question. The Q is about programming. Commented Jun 30, 2023 at 8:07

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.