Saturday 14 May 2016

qgis - Merge all shp files in a folder into one with a new field populated with the source filename


Want to merge all shp files in a folder into one with a new field populated with the source filename. Not getting any errors but not getting any outputs.


Code originally taken from (How to add field with filename when merging shapefiles with ogr2ogr?)


# merge_shps.py
import os
path = "C:\TEMP\SWS_SUDS\Cadastral_Maps" # path to your folder of .shp files
merge = "SWS_INSPIRE" # this will be the name of your merged result
directory = os.listdir(path)
count = 0
for filename in directory:

print "\n" + filename + "\n"
if ".SHP" in filename.upper() and not ".XML" in filename.upper():
# On the first pass, create a clone and add the filename column.
if count == 0:
# Make a clone (matt wilkie)..
cmd = 'ogr2ogr ' + path + '\\' + merge + '.shp ' + path + '\\' + filename + ' -where "FID < 0"'
print "\n" + cmd + "\n"
os.system(cmd)
# Add the field (j03lar50n)..
cmd = 'ogrinfo ' + path + '\\' + merge + '.shp -sql "ALTER TABLE ' + merge + ' ADD COLUMN filename character(50)"'

print "\n" + cmd + "\n"
os.system(cmd)
# Now populate the data (capooti)..
print "Merging: " + str(filename)
# You'll need the filename without the .shp extension for the OGR_SQL..
filenameNoExt = filename.replace(".shp","")
cmd = 'ogr2ogr -f "esri shapefile" -update -append "' + \
path + '\\' + merge + '.shp" "' + \
path + '\\' + filename +'"' \
' -sql "SELECT \'' + filename + '\' AS filename, * FROM ' + filenameNoExt + '"'

# Uncomment this line to spit the ogr2ogr sentence to the terminal..
print "\n" + cmd + "\n"
os.system(cmd)
count += 1


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...