Monday, 6 November 2017

QgsVectorFileWriter.writeAsVectorFormat differents QGIS 2 QGIS 3


A long time ago I wrote a plugin for my own use. The plugin works fine in QGIS 2.18 but not in QGIS 3.1. I used the script 2to3 and solved most problems.The only problem I am left with is the following.


First my code that I use.


import os.path

CSVDIR = 'd:/QGIS/Temp_map/TestCSV/2018/'
DESTDIR = 'd:/QGIS/Temp_map/TestSHP/2018/'


if not os.path.exists(DESTDIR):
os.makedirs(DESTDIR)

for root, dirs, files in os.walk(CSVDIR):
for file in files:
if file.endswith('.csv'):
fullname = os.path.join(root, file).replace('/', '/')
filename = os.path.splitext(os.path.basename(fullname))[0]
uri = 'file:///%s?crs=%s&delimiter=%s&xField=%s&yField=%s&decimal=%s&useHeader=no&' % (fullname, 'EPSG:4326', ';', 'Field_7', 'Field_6', ',')
layer = QgsVectorLayer(uri, 'my_layer', 'delimitedtext')

QgsVectorFileWriter.writeAsVectorFormat(layer, DESTDIR + filename + '.shp', 'CP1250', None, 'ESRI Shapefile')

self.iface.messageBar().clearWidgets()
self.iface.mapCanvas().refresh()

QMessageBox.information(iface.mainWindow(), "CSV naar Shape",
"Uw Shapefiles zijn aangemaakt!", QMessageBox.Ok )

This code works in QGIS 2.18 but give the following error in QGIS 3.0.


Traceback (most recent call last):

File "C:\PROGRA~1\QGIS3~1.0\apps\Python36\lib\code.py", line 91, in runcode
exec(code, self.locals)
File "", line 1, in
File "", line 24, in
TypeError: QgsVectorFileWriter.writeAsVectorFormat(): arguments did not match any overloaded call:
overload 1: argument 4 has unexpected type 'NoneType'
overload 2: argument 4 has unexpected type 'NoneType'
overload 3: argument 3 has unexpected type 'str'

What can I do to make this working?




Answer



writeAsVectorFormat() function expects QgsCoordinateReferenceSystemfor argument 4.


Replacing None with layer.crs() will solve your problem.


For more information, refer to QgsVectorFileWriter Class Reference


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...