2

I am using QGIS 2.10 (but I've also tried 2.8) to loop through all the shapefiles in a folder (those ending in .shp) and perform a dissolve function on each of them. However, when I run the following code in QGIS it crashes the program. If I run the code outside of QGIS, the QgsGeometryAnalyzer().dissolve function returns 'False'.

Strangely, the same processes work outside of a loop. For example, if I load a shapefile using the QgsVectorLayer function and perform a dissolve using the QgsGeometryAnalyzer().dissolve function everything operates correctly.

Is there something I'm missing here?

import os
from qgis.core import *
from qgis.analysis import *

files = os.listdir('C:/Temp')

for file in files:
    if file[-3:] == 'shp':
        layer = QgsVectorLayer(file, file[:-4], 'ogr')
        QgsGeometryAnalyzer().dissolve(layer, 'C:/Temp/Dissolved/' + file[:-4]+"_dissolved")

*Also, I should note that I've tried to do the same process with GRASS using the v.dissolve command. Unfortunately, this doesn't merge/dissolve polygons that are not overlapping. I need all of the polygons in a shapefile to become one multipart polygon.

1 Answer 1

3

Never used the QgsGeometryAnalyzer() method before (I should take a look at this) but you could use the following code which I think should do what your code does (tested this on Python Console in QGIS 2.8.2):

import processing, os, glob

result_path = "C:\Temp\Dissolved\\"
os.chdir("C:\Temp\\")

for fname in glob.glob("*.shp"):

    name= list(os.path.splitext(fname))
    name[0] = name[0] + "_dissolved"
    newName = "".join(name)
    processing.runalg('qgis:dissolve', fname, 'True', '', result_path + newName)

Hope this helps!

2
  • 1
    This worked! Thank you so much. The processing function seems to be a much slicker method of running QGIS tools in python. Thank you for sharing!
    – Joe R.
    Commented Jul 14, 2015 at 21:48
  • @JoeR. - Awesome buddy, glad it's working for you and most welcome! Yes, the processing function is very useful when it comes to writing commands, saves a lot of time in my opinion :)
    – Joseph
    Commented Jul 15, 2015 at 8:58

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.