2

I have many folders (which represent different countries) which all contain the same shapefile types (e. g. schools, hospitals, streets etc.). The shapefiles also share the exact same names in every folder (every countryfolder has a shapefile named 'schools'). I want to merge all shapefiles which share the same name (e.g. merge the shapefile 'schools' in the US subfolder with the shapefile 'schools' in the Canada subfolder an so on). This should happen for all duplicate shapefiles automatically.

Has anyone an idea how to do it (maybe with a code example)? I thought about a nested for-loop or a search cursor, but I have no idea how to apply it.

I'm using ArcGIS Pro 2.9.3

3
  • Copy the templates and Append the rest. No need to mess with cursors yet. This is more a list compilation in Python issue than an ArcPy thing.
    – Vince
    Aug 15, 2022 at 14:13
  • What do you mean by that exactly? Would this be a manual approach? Because this would take me hours of work.
    – Radde1683
    Aug 15, 2022 at 14:15
  • No, it's just list walking. Choose a master folder. For each shapefile name, walk the folders to identify other sources, then pass the list of other sources into Append. Ten, twenty lines at most. You do have to be certain all the fields are the same and in the same order (otherwise this becomes days of work).
    – Vince
    Aug 15, 2022 at 14:26

1 Answer 1

1

You can list all shapefiles using os.walk, group them with collections defaultdict and merge:

import os, arcpy
from collections import defaultdict

shapes = defaultdict(list)
infolder = r'C:\GIS\temp\Test'
outfolder = r'C:\GIS\temp'
for root, folder, files in os.walk(infolder):
    for file in files:
        if file.endswith('.shp'):
            fullname = os.path.join(root, file)
            #print(fullname)
            #C:\GIS\temp\Test\denmark\zg_riks.shp
            #C:\GIS\temp\Test\denmark\zl_riks.shp
            #C:\GIS\temp\Test\sweden\zg_riks.shp
            #C:\GIS\temp\Test\sweden\zl_riks.shp
            group = file.split('.')[0]
            shapes[group].append(fullname)
for g, shapelist in shapes.items():
    #print(g) #zg_riks
    #print(shapelist) #['C:\\GIS\\temp\\Test\\denmark\\zg_riks.shp', 'C:\\GIS\\temp\\Test\\sweden\\zg_riks.shp']
    arcpy.Merge_management(inputs=shapelist, output=os.path.join(outfolder, g))

enter image description here

Output enter image description here

0

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.