Hi all,
I'm back at it again. I've written a script to Iterate through an MXD and export all features within 50 miles of my state to a feature class. There are over 550 FCs to process and it keeps failing due to invalid characters. Does arcpy offer a way to parse out invalid characters when naming a conversion output?
Below is the code i'm referencing
import arcpy import glob import os files = glob.glob(r'C:\Users\JOC-001\Documents\GIS\HSIP\IL_Infrastructure2015\*') for f in files: os.remove(f) mxd = arcpy.mapping.MapDocument(r'C:\Users\JOC-001\Documents\GIS\HSIP\Infrastructure\HSIP_Gold_2015_Infrastructure.mxd') layers = arcpy.mapping.ListLayers(mxd) for lyr in layers: if lyr.isGroupLayer: pass else: print lyr arcpy.SelectLayerByLocation_management(lyr, "WITHIN_A_DISTANCE", r"C:\Users\JOC-001\Documents\ArcGIS\Default.gdb\Illinois", "50 Miles", "NEW_SELECTION") arcpy.FeatureClassToFeatureClass_conversion(lyr, r'C:\Users\JOC-001\Documents\GIS\HSIP\IL_Infrastructure2015', str(lyr.name))
Solved! Go to Solution.
I have also used lyr.longName, as this has a slash between the group name and the layer name. While this isn't a safe character for output, it is a handy way to separate the names sometimes.
for example, I have a script which creates layer files from an mxd, and to identify if a layer is in a group (rather than being a group layer) I use the following and change the output name accordingly (as I am outputting all layers - stand alone, group layers and sub layers and there is a high likelihood of duplicate names):
if lyr.longName.find("\\") > -1:
# change the name
out_lyr = lyr.longName.replace("\\","_")
# or, functionally the same
out_lyr = arcpy.validateTablename(lyr.longName)
GroupLayer\Layer becomes GroupLayer_Layer.
For generating unique output names I do an Exists() check, and increment a counter at the end of the name as necessary.
Six years later, the solution worked like a charm.
As a bit of background, I was creating individual FC's from a larger FC based on an attribute.
The MB failed due to spaces & dashes in the attribute name. As a workaround, I created a new field and calculated using the following expression.
import re
def strip_invalid(plant):
x = re.sub('[^A-Za-z0-9]+', '', plant)
return x
Thanks, @JoshuaBixby !!
arcpy.ValidateTableName does a good job of removing problematic characters as well.