1

I previously had a script in 2.18 that exported csv files with kml geometry's file by file. I'm now wanting to move to QGIS 3 and do the same process except Merge the point layers then add the geometry field then export to csv

This is my 2.18 script - it does not preform the merging but does everything else I am after

import os, processing,ogr,csv,sys
from qgis.core import QgsMapLayerRegistry
from qgis.utils import iface

crs = 'EPSG:4326'  

#shapefiles = QgsMapLayerRegistry.instance().mapLayers().values()  #All Map Layers
shapefiles = QgsMapLayerRegistry.instance().mapLayers()
shapefiles = iface.legendInterface().selectedLayers()
shapefiles = iface.legendInterface().layers()

excludeshapes1 = 'copy'
excludeshapes2 = 'parcel'
excludeshapes3 = 'contour'
excludeshapes4 = 'road'
excludeshapes5 = 'address'

for shapes in shapefiles:
    sname =shapes.name().lower()
    print sname 
    print "Shape Type"
    print shapes.type()
    if excludeshapes1 not in sname and excludeshapes2 not in sname and excludeshapes3 not in sname and excludeshapes4 not in sname and excludeshapes5 not in sname:
        if shapes.type() == 0:
            print "WKB Type"
            print shapes.wkbType() 
        #print shapes.name()
        sname =shapes.name()

        #print sname 
        #print shapes.type() == QgsMapLayer.VectorLayer
        if shapes.type() == 0:
            if shapes.wkbType() ==0:
               print " WKBUnknown"  
            elif shapes.wkbType() == 100:
                print " No Geom"  
            elif shapes.wkbType() == 1 or shapes.wkbType() == 4:
                print " Point" 
                try:
                    myfilepath = shapes.dataProvider().dataSourceUri()
                    (myDirectory,nameFile) = os.path.split(myfilepath)
                    csvfile= myDirectory + "/" + "WGS84_Point" + shapes.name()+".csv"
                    processing.runalg("qgis:reprojectlayer", shapes, crs, myDirectory + "/" + "WGS84_Point" + shapes.name())
                    #Open files
                    daShapefile =  myDirectory+"/" + "WGS84_Point"+shapes.name()+".shp"
                    driver = ogr.GetDriverByName('ESRI Shapefile')
                    dataSource = driver.Open(daShapefile, 0) # 0 means read-only. 1 means writeable.
                    csvfile=open(csvfile,'wb')
                    ds=ogr.Open(daShapefile)
                    lyr=ds.GetLayer()

                    #Get field names
                    dfn=lyr.GetLayerDefn()
                    nfields=dfn.GetFieldCount()
                    fields=[]
                    for i in range(nfields):
                        fields.append(dfn.GetFieldDefn(i).GetName())
                    fields.append('kmlgeometry')
                    csvwriter = csv.DictWriter(csvfile, fields)
                    try:csvwriter.writeheader() #python 2.7+
                    except:csvfile.write(','.join(fields)+'\n')

                    # Write attributes and kml out to csv
                    for feat in lyr:
                            if feat.GetGeometryRef() is None:
                                print("No Valid Geometry" )
                            else:
                                attributes=feat.items()
                                geom=feat.GetGeometryRef()
                                attributes['kmlgeometry']=geom.ExportToKML()
                                csvwriter.writerow(attributes)


                    #clean up
                    del csvwriter,lyr,ds
                    csvfile.close()
                except:
                    pass
            elif shapes.wkbType() == 2 or  shapes.wkbType() == 5 :
                print " Line" 
                try:
                    myfilepath = shapes.dataProvider().dataSourceUri()
                    (myDirectory,nameFile) = os.path.split(myfilepath)
                    csvfile= myDirectory + "/" + "WGS84_Line" + shapes.name()+".csv"
                    processing.runalg("qgis:reprojectlayer", shapes, crs, myDirectory + "/" + "WGS84_Line" + shapes.name())
                    #Open files
                    daShapefile =  myDirectory+"/" + "WGS84_Line"+shapes.name()+".shp"
                    driver = ogr.GetDriverByName('ESRI Shapefile')
                    dataSource = driver.Open(daShapefile, 0) # 0 means read-only. 1 means writeable.
                    csvfile=open(csvfile,'wb')
                    ds=ogr.Open(daShapefile)
                    lyr=ds.GetLayer()

                    #Get field names
                    dfn=lyr.GetLayerDefn()
                    nfields=dfn.GetFieldCount()
                    fields=[]
                    for i in range(nfields):
                        fields.append(dfn.GetFieldDefn(i).GetName())
                    fields.append('kmlgeometry')
                    csvwriter = csv.DictWriter(csvfile, fields)
                    try:csvwriter.writeheader() #python 2.7+
                    except:csvfile.write(','.join(fields)+'\n')

                    # Write attributes and kml out to csv
                    for feat in lyr:
                            if feat.GetGeometryRef() is None:
                                print("No Valid Geometry" )
                            else:
                                attributes=feat.items()
                                geom=feat.GetGeometryRef()
                                attributes['kmlgeometry']=geom.ExportToKML()
                                csvwriter.writerow(attributes)


                    #clean up
                    del csvwriter,lyr,ds
                    csvfile.close()
                except:
                    pass
            elif shapes.wkbType() == 3 or shapes.wkbType() == 6:  
                print " Polygon" 
                try:
                    myfilepath = shapes.dataProvider().dataSourceUri()
                    (myDirectory,nameFile) = os.path.split(myfilepath)
                    csvfile= myDirectory + "/" + "WGS84_Polygon" + shapes.name()+".csv"
                    processing.runalg("qgis:reprojectlayer", shapes, crs, myDirectory + "/" + "WGS84_Polygon" + shapes.name())
                    #Open files
                    daShapefile =  myDirectory+"/" + "WGS84_Polygon"+shapes.name()+".shp"
                    driver = ogr.GetDriverByName('ESRI Shapefile')
                    dataSource = driver.Open(daShapefile, 0) # 0 means read-only. 1 means writeable.
                    csvfile=open(csvfile,'wb')
                    ds=ogr.Open(daShapefile)
                    lyr=ds.GetLayer()

                    #Get field names
                    dfn=lyr.GetLayerDefn()
                    nfields=dfn.GetFieldCount()
                    fields=[]
                    for i in range(nfields):
                        fields.append(dfn.GetFieldDefn(i).GetName())
                    fields.append('kmlgeometry')
                    csvwriter = csv.DictWriter(csvfile, fields)
                    try:csvwriter.writeheader() #python 2.7+
                    except:csvfile.write(','.join(fields)+'\n')

                    # Write attributes and kml out to csv
                    for feat in lyr:
                            if feat.GetGeometryRef() is None:
                                print("No Valid Geometry" )
                            else:
                                attributes=feat.items()
                                geom=feat.GetGeometryRef()
                                attributes['kmlgeometry']=geom.ExportToKML()
                                csvwriter.writerow(attributes)


                    #clean up
                    del csvwriter,lyr,ds
                    csvfile.close()
                except:
                    pass
            elif shapes.wkbType() < 0 or shapes.wkbType() > 6:
                try:
                    print ("Not Processed Layer: ") + sname
                    print ("Not Processed-WKBType: ") + shapes.wkbType() 
                except:
                    pass

            else:
                print sname
                raise Exception('Should never happen')

I know there are options avaible in QGIS3 like mergevetorlayers and reprojectlayer.

0

there are some changes in the Qgis Python API (see https://qgis.org/api/api_break.html), for example QgsMapLayerRegistry does not exist anymore. Change the first lines into:

group =QgsProject.instance().layerTreeRoot().children()
shapefiles = [ item.layer() for item in group ] #list of all layers

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.