Sunday, 29 March 2015

Merge shapefiles in folders and subfolders with arcpy



I try to merge 20 shapefiles in order to get one shapefile that include all the features. All shapefiles are called "migrashim", and they spread in big folder that divided to a lot of sub folders. My code is:


import arcpy,os,sys,string,fnmatch
import arcpy.mapping
from arcpy import env

rootPath = 'C:\Project\layers'
pattern = 'migrashim.shp'
counter = 0
for root, dirs, files in os.walk(rootPath):
for filename in fnmatch.filter(files, pattern):

print( os.path.join(root, filename))
arcpy.Merge_management(["migrashim.shp"], r"C:\Project\layers\migrashim_total.shp")
counter = counter + 1
print counter

and i get an error:



ERROR 000732: Input Datasets: Dataset migrashim.shp does not exist or is not supported Failed to execute (Merge).




Answer




So currently you're using the input of your shape file name but not indicating a directory. The full path is needed for the merge to work. Or you can set your environment's workspace each time you find a file. You're also not actually merging anything, since you have only a single input.


I'd populate a list of all the matches found, so that you can use it to perform a single merge at the end of your code.


Try something like this:


matches = []

for root, dirs, files in os.walk(rootPath):
for filename in files:
if filename == "migrashim.shp":
match = ( os.path.join(root, filename))
matches.append (match)

counter = counter + 1

arcpy.Merge_management(matches, r"C:\Project\layers\migrashim_total.shp")

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