3

In QGIS 3.16 I'm trying to load all shapefiles from a folder and subfolders and export all to KMLs files in a single folder (The shapefiles have different names).

This error appears, but I don't understand what I can do to resolve this:

TypeError: QgsVectorFileWriter.writeAsVectorFormat():
arguments did not match any overloaded call:
  overload 1: argument 1 has unexpected type 'str'
  overload 2: argument 1 has unexpected type 'str'
  overload 3: argument 1 has unexpected type 'str'

And the code is:

import os
    
input_folder = 'D:\python_dados_av1'
output_folder = 'D:\teste'
    
layers = [] 
for root, folder, files in os.walk(input_folder):
    for file in files:
        if file.endswith('.shp'):
            fullname = os.path.join(root, file)
            rename_shp = 'convert_%s' % (file)
            newfile = os.path.join(output_folder,rename_shp)
            layers.append(QgsVectorLayer(fullname, file.split('.')[0]))
            QgsVectorFileWriter.writeAsVectorFormat(file, newfile, "utf-8", "KML")
0

1 Answer 1

8

According to the documentation the first argument should be a QgsVectorLayer, which is why you are getting the unexpected type error.

You are also missing the QgsCoordinateReferenceSystem parameter.

This should work:

import os

layers = [] 
for root, folder, files in os.walk(input_folder):
    for file in files:
        if file.endswith('.shp'):
            fullname = os.path.join(root, file)
            rename_shp = 'convert_%s' % (file)
            newfile = os.path.join(output_folder,rename_shp)

            # assign the QgsVectorLayer you make to a variable which you can then pass to the QgsVectorFileWriter
            tmp_lyr = QgsVectorLayer(fullname, file.split('.')[0])
            layers.append(tmp_lyr)
            
            # get the CRS from the layer
            crs = tmp_lyr.crs()  
            QgsVectorFileWriter.writeAsVectorFormat(tmp_lyr, newfile, "utf-8", crs, "KML")
0

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.