I'm trying to save all layers in my mxd as .lyr files using the script below. However, I'm getting an error because some layer names contain special characters (e.g. © : * ) and cannot be written into file names. How can I make sure special characters are ignored/replaced?
Can't you just rename them in the table of contents sans the special characters? I did it and go this result:
import arcpy mxd = arcpy.mapping.MapDocument("CURRENT") for lyr in arcpy.mapping.ListLayers(mxd): print lyr.name '''' returns : Bonneville_Shoreline_Trail RegionalTrails_1 Trails'''' ''' name change''' for lyr in arcpy.mapping.ListLayers(mxd): print lyr.name ''' returns: BonnevilleShorelineTrail <- note name change RegionalTrails_1 Trails '''
I'm hoping there is a way to edit the script so that it will ignore special characters when naming the new .lyr files. My mxd contains over 100 different layers so manually changing the layer names to remove any special characters would be extremely time consuming. Some symbols, like the copyright symbol, are also quite important so would only like them removed in the file name, not the layer name.
Take a look at ValidateTableName—ArcPy Functions | ArcGIS Desktop . If you don't pass a workspace, it will simply validate the name you pass it. By the way, the copyright symbol is valid, so it should not be throwing an error.
You are right, the problem wasn't with the file names. Problem is you can't have special characters in folder names so it's still throwing an error when it comes across a group with special characters...
IMHO special characters are worse than under cooked hash browns. Here's another example of how they can spoil an oherwise perfect day https://community.esri.com/thread/232565-mystery-with-excel-files ....
See if using this regular expression works for you (adapted from How to remove bad path characters in Python? - Stack Overflow :(
>>> import re >>> >>> pattern = '[^:\\\ \w\-_\.]' >>> bad_lyr_path = r"C:\tmp\esri©\layers,mxds\mylayer.lyr" >>> >>> print(re.sub(pattern, "_", bad_lyr_path)) C:\tmp\esri_\layers_mxds\mylayer.lyr >>>