This is what I'm trying to run:
import sys, glob
# Prepare the environment
from qgis.core import * # qgis.core must be imported before PyQt4.QtGui!!!
from PyQt4.QtGui import *
app = QApplication([])
QgsApplication.setPrefixPath("/usr/bin/qgis", True) # The True value is important
QgsApplication.initQgis()
# Prepare processing framework
from processing.core.Processing import Processing
Processing.initialize()
from processing.tools import *
from osgeo import ogr
driver = ogr.GetDriverByName('ESRI Shapefile')
driver2 = ogr.GetDriverByName('ESRI Shapefile')
dataSource = driver.Open("file1.shp", 1) #1 is read/write
dataSource2 = driver.Open("file2.shp", 1) #1 is read/write
layer1 = dataSource.GetLayer()
layer2 = dataSource.GetLayer()
Processing.runAlgorithm("qgis:mergevectorlayers", layer1, layer2, '/home/name/Desktop/output.shp')
But I get this error:
[Finished in 0.2s with exit code 1]
[shell_cmd: python -u "/home/none/Desktop/testattribute/merged.py"]
[dir: /home/name/Desktop/testattribute]
[path: /home/name/torch/install/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games]
I'm using Processing 2.12.2.
Now I'm running this code from @gene with the addition that I'm trying to use it in a loop that iterates through a list of shapefiles:
meta = fiona.open(filelist[0]).meta
for shapefile in filelist:
with fiona.open(exportname, 'w', **meta) as output:
for features in fiona.open(shapefile):
output.write(features)
But I do not end up with a valid shapefile. What am I doing wrong?
I ended up sorting it out into a somewhat hacked looking script.
def mergeshp(firstshp, secondshp, index):
exportname = 'mergeshp_' + str(index) + '.shp'
meta = fiona.open(firstshp).meta
with fiona.open(exportname , 'w', **meta) as output:
for features in fiona.open(firstshp):
output.write(features)
for features in fiona.open(secondshp):
output.write(features)
return exportname
And I called it with this code:
numfiles = len(shapelist)
i=0
mergedshp = mergeshp(shapelist[i],shapelist[i+1], i)
i += 2
while i<numfiles:
mergedshp = mergeshp(mergedshp, shapelist[i], i)
i += 1