2

I'm a new user of ArcMap. And I'm not good at programming language.

There are the following shapefiles in workspace.

L01-1983_01.shp
L01-1983_02.shp
...
L01-1983_46.shp
L01-1983_47.shp
L01-1984_01.shp
L01-1984_02.shp
...
L01-1984_46.shp
L01-1984_47.shp
...
L01-2012_01.shp
L01-2012_02.shp
...
L01-2012_46.shp
L01-2012_47.shp
L01-2013_01.shp
L01-2013_02.shp
...
L01-2013_46.shp
L01-2013_47.shp

File name has the following rule.

L01-(year)_(city code).shp

I want to merge all shapefiles for each year, for example,

L01-1983_01.shp
L01-1983_02.shp
...
L01-1983_46.shp
L01-1983_47.shp
-----merge----    L01_1983.shp
...
L01-2013_01.shp
L01-2013_02.shp
...
L01-2013_46.shp
L01-2013_47.shp
-----merge----    L01_2013.shp

Below is my script.

list_year=["list_%d" % x for x in range(1983,2014)]
year=1983
for i in list_year:
    i=ListFeatureClasses("*year*")
    year=year+1
years=range(1983,2014)
for i in years:
    Merge_management(list_i,"L01_i.shp")

But I can't get merged files.

How can I write python script to merge shapefiles using a loop?

  • This should get you started. – Paul Jun 11 '14 at 12:42
3

Something like this should work for you.

import arcpy
arcpy.env.overwriteOutput = True

in_folder = r"C:\GIS\Temp"
arcpy.env.workspace = in_folder

years = list(range(1983,2014))

for year in years:
    shp_paths = []
    list_shps = arcpy.ListFeatureClasses("*{0}*".format(year))
    if list_shps:
        for shp in list_shps:
            desc = arcpy.Describe(shp)
            shppath = desc.catalogPath
            shp_paths.append(shppath)
        print shp_paths
        arcpy.Merge_management(shp_paths,"L01_{0}".format(year))
  • Thank you for your answer. But, as your script, I can't get merged files. – Kang Jun 11 '14 at 13:14
  • 1
    You have not copied the code as it is (at least it doesn't look right in the question body). Refer to the Esri Help pages to read more about Python scripting if you need adjust your code further to meet your needs. – Alex Tereshenkov Jun 11 '14 at 13:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.