Update layers with group name and batch define projections using ArcPy

Since these two scripts are tiny (more like code snippets), I decided to plug them both today. First one:

#
# @date 29/05/2015
# @author Cindy Williams
#
# Updates a layer name with the name of the group layer
# it is in, in an existing mxd.
#
# For use in the Python window in ArcMap.
#
import arcpy
mxd = arcpy.mapping.MapDocument("CURRENT")
lyrs = [lyr for lyr in arcpy.mapping.ListLayers(mxd) if lyr.isFeatureLayer]
for lyr in lyrs:
lyr.name = lyr.name + "_" + lyr.longName.split("\\")[0]
arcpy.RefreshTOC()
mxd.save()

As often happens with these Gists, I need to solve some problem which would be tedious to do manually, or it’s a batch process (or both). I also normally forget the reason why I needed to solve the problem in the first place, because I get so happy when coding.

I’m pretty sure I wrote this because of some issue with Asset Management data. In fact, most of my short snippets are to solve some issue I’m having with Asset Management data. This Gist is very straightforward: In Line 14, I grab all the feature layers within a map document, and in Line 17 I update the name of the feature layer with the name of the group layer that it is in. This of course assumes that all the feature layers within the mxd are in group layers, but the script should not fall over if there are feature layers which are not grouped.

Most of the time, my scripts are for very specific cases. If I’m writing a Python toolbox, that’s when I will include error checking, validation, testing etc. Second one:

import arcpy
arcpy.env.workspace = r"C:\Some\Arb\Folder"
# Define spatial reference WGS 84
sr = arcpy.SpatialReference(4326)
for shp in arcpy.ListFeatureClasses():
arcpy.management.DefineProjection(shp, sr)
print("Defined " + shp)
print("Script complete").

While there is a Batch Project tool included in the Data Management toolbox, there isn’t one to Define Projection for multiple feature classes. I often need to use this snippet when I receive new Asset Management GIS data, because the client does not have access to ArcGIS (or GIS in general), or edited the shapefile dbfs in Excel, or did a series of things to the data so that it lost its projection information. In Line 8, I call the ListFeatureClasses() function. I normally prefer to use arcpy.da.Walk() (or os.walk()), but for a small script like this it’s fine.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.